<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>Angular7入门总结篇 | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="JavaScript,Angular,">
  

  <meta name="description" content="最近在学Ionic4，不得不学习angular、Typescript基础知识，这里简单总结记录一下。  一、Angular 介绍 Angualr 是一款来自谷歌的开源的 web 前端框架，诞生于 2009 年，由 Misko Hevery 等 人创建，后为 Google 所收购。是一款优秀的前端 JS 框架，已经被用于 Google 的多款产品当中。   根据项目数统计 angular(1.x">
<meta name="keywords" content="JavaScript,Angular">
<meta property="og:type" content="article">
<meta property="og:title" content="Angular7入门总结篇">
<meta property="og:url" content="http://blog.poetries.top/2019/01/09/angular7-intro-summary/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="最近在学Ionic4，不得不学习angular、Typescript基础知识，这里简单总结记录一下。  一、Angular 介绍 Angualr 是一款来自谷歌的开源的 web 前端框架，诞生于 2009 年，由 Misko Hevery 等 人创建，后为 Google 所收购。是一款优秀的前端 JS 框架，已经被用于 Google 的多款产品当中。   根据项目数统计 angular(1.x">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/17.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/18.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/19.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/20.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/21.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/22.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/23.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/24.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/25.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/26.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/27.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/28.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/29.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/30.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/31.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/32.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/33.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/34.png">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/1480597-7e0081f4616fe461.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/35.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/36.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/37.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/38.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/39.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/40.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/41.png">
<meta property="og:updated_time" content="2020-08-15T04:25:31.902Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Angular7入门总结篇">
<meta name="twitter:description" content="最近在学Ionic4，不得不学习angular、Typescript基础知识，这里简单总结记录一下。  一、Angular 介绍 Angualr 是一款来自谷歌的开源的 web 前端框架，诞生于 2009 年，由 Misko Hevery 等 人创建，后为 Google 所收购。是一款优秀的前端 JS 框架，已经被用于 Google 的多款产品当中。   根据项目数统计 angular(1.x">
<meta name="twitter:image" content="https://poetries1.gitee.io/img-repo/20191001/17.png">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#一、Angular-介绍"><span class="toc-text">一、Angular 介绍</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#二、Angular-环境搭建及创建项目"><span class="toc-text">二、Angular 环境搭建及创建项目</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#2-1-环境搭建"><span class="toc-text">2.1 环境搭建</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-2-创建项目"><span class="toc-text">2.2 创建项目</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-3-目录结构分析"><span class="toc-text">2.3 目录结构分析</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-4-Angular-cli"><span class="toc-text">2.4 Angular cli</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#三、angular组件及组件里的模板"><span class="toc-text">三、angular组件及组件里的模板</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#3-1-创建angualr组件"><span class="toc-text">3.1 创建angualr组件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-2-Angular-绑定数据"><span class="toc-text">3.2 Angular 绑定数据</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-3-声明属性的几种方式"><span class="toc-text">3.3 声明属性的几种方式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-4-绑定属性"><span class="toc-text">3.4 绑定属性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-5-数据循环-ngFor"><span class="toc-text">3.5 数据循环 *ngFor</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-6-条件判断-ngIf"><span class="toc-text">3.6 条件判断 *ngIf</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-7-ngSwitch"><span class="toc-text">3.7 *ngSwitch</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-8-执行事件-click-”getData-”"><span class="toc-text">3.8 执行事件 (click)=”getData()”</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-9-表单事件"><span class="toc-text">3.9 表单事件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-10-双向数据绑定"><span class="toc-text">3.10 双向数据绑定</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-11-ngClass-、-ngStyle"><span class="toc-text">3. 11 [ngClass]、[ngStyle]</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-12-管道"><span class="toc-text">3.12 管道</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-13-实现一个人员登记表单-案例"><span class="toc-text">3.13 实现一个人员登记表单-案例</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-14-实现一个完整的ToDo-案例"><span class="toc-text">3.14 实现一个完整的ToDo-案例</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-15-搜索缓存数据-案例"><span class="toc-text">3.15 搜索缓存数据-案例</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#四、Angular-中的服务"><span class="toc-text">四、Angular 中的服务</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#4-1-服务"><span class="toc-text">4.1 服务</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-2-改造上面的Todo、searchList"><span class="toc-text">4.2 改造上面的Todo、searchList</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#五、Dom-操作以及-ViewChild、-执行-css3-动画"><span class="toc-text">五、Dom 操作以及@ViewChild、 执行 css3 动画</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#六、Angular-父子组件以及组件之间通讯"><span class="toc-text">六、Angular 父子组件以及组件之间通讯</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#6-1-父组件给子组件传值-input"><span class="toc-text">6.1 父组件给子组件传值-@input</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-2-子组件通过-Output-触发父组件的方法（了解）"><span class="toc-text">6.2 子组件通过@Output 触发父组件的方法（了解）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-3-父组件通过-ViewChild-主动获取子组-件的数据和方法"><span class="toc-text">6.3 父组件通过@ViewChild 主动获取子组 件的数据和方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-4-非父子组件通讯"><span class="toc-text">6.4 非父子组件通讯</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#七、Angular-中的生命周期函数"><span class="toc-text">七、Angular 中的生命周期函数</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#7-1-Angular中的生命周期函数"><span class="toc-text">7.1 Angular中的生命周期函数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7-2-生命周期钩子详解"><span class="toc-text">7.2 生命周期钩子详解</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#7-2-1-constructor-掌握"><span class="toc-text">7.2.1 constructor-掌握</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-2-2-ngOnChanges"><span class="toc-text">7.2.2  ngOnChanges()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-2-3-ngOnInit-–掌握"><span class="toc-text">7.2.3 ngOnInit()–掌握</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-2-4-ngDoCheck"><span class="toc-text">7.2.4 ngDoCheck()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-2-5-ngAfterContentInit"><span class="toc-text">7.2.5 ngAfterContentInit()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-2-6-ngAfterContentChecked"><span class="toc-text">7.2.6 ngAfterContentChecked()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-2-7-ngAfterViewInit-–掌握"><span class="toc-text">7.2.7 ngAfterViewInit()–掌握</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-2-8-ngAfterViewChecked"><span class="toc-text">7.2.8 ngAfterViewChecked()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-2-9-ngOnDestroy-–掌握"><span class="toc-text">7.2.9 ngOnDestroy()–掌握</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#八、Rxjs-异步数据流编程"><span class="toc-text">八、Rxjs 异步数据流编程</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#8-1-Rxjs介绍"><span class="toc-text">8.1 Rxjs介绍</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8-2-Promise和RxJS处理异步对比"><span class="toc-text">8.2 Promise和RxJS处理异步对比</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8-3-Rxjs-unsubscribe-取消订阅"><span class="toc-text">8.3 Rxjs unsubscribe 取消订阅</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8-4-Rxjs-订阅后多次执行"><span class="toc-text">8.4 Rxjs 订阅后多次执行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8-5-Angualr6-x之前使用Rxjs的工具函数-map-filter"><span class="toc-text">8.5 Angualr6.x之前使用Rxjs的工具函数 map filter</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8-6-Angualr6-x-以后-Rxjs6-x-的变化以及-使用"><span class="toc-text">8.6 Angualr6.x 以后 Rxjs6.x 的变化以及 使用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#8-6-1-Rxjs-的变化参考"><span class="toc-text">8.6.1 Rxjs 的变化参考</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8-7-Rxjs-延迟执行"><span class="toc-text">8.7 Rxjs 延迟执行</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#九、Angular-中的数据交互-get-jsonp-post"><span class="toc-text">九、Angular 中的数据交互(get jsonp post)</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#9-1-Angular-get-请求数据"><span class="toc-text">9.1 Angular get 请求数据</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#9-2-Angular-post-提交数据"><span class="toc-text">9.2 Angular post 提交数据</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#9-3-Angular-Jsonp-请求数据"><span class="toc-text">9.3 Angular Jsonp 请求数据</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#9-4-Angular-中使用第三方模块-axios-请求数据"><span class="toc-text">9.4 Angular 中使用第三方模块 axios 请求数据</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#十、Angular-中的路由"><span class="toc-text">十、Angular 中的路由</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#10-1-Angular-创建一个默认带路由的项目"><span class="toc-text">10.1 Angular 创建一个默认带路由的项目</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#10-2-routerLink-跳转页面-默认路由"><span class="toc-text">10.2 routerLink 跳转页面 默认路由</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#10-3-routerLinkActive-设置routerLink-默认选中路由"><span class="toc-text">10.3 routerLinkActive 设置routerLink 默认选中路由</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#10-4-routerLink-Get传递参数"><span class="toc-text">10.4 routerLink Get传递参数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#10-5-动态路由"><span class="toc-text">10.5 动态路由</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#10-6-动态路由的-js-跳转"><span class="toc-text">10.6 动态路由的 js 跳转</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#10-7-路由-get-传值-js-跳转"><span class="toc-text">10.7 路由 get 传值 js 跳转</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#10-8-父子路由"><span class="toc-text">10.8 父子路由</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#十一、更多参考"><span class="toc-text">十一、更多参考</span></a></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-angular7-intro-summary" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">Angular7入门总结篇</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2019.01.09</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 9.7k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 46分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <blockquote>
<p>最近在学<code>Ionic4</code>，不得不学习<code>angular</code>、<code>Typescript</code>基础知识，这里简单总结记录一下。</p>
</blockquote>
<h1 id="一、Angular-介绍"><a href="#一、Angular-介绍" class="headerlink" title="一、Angular 介绍"></a>一、Angular 介绍</h1><blockquote>
<p><code>Angualr</code> 是一款来自谷歌的开源的 <code>web</code> 前端框架，诞生于 <code>2009</code> 年，由 <code>Misko Hevery</code> 等 人创建，后为 <code>Google</code> 所收购。是一款优秀的前端 <code>JS</code> 框架，已经被用于 <code>Google</code> 的多款产品当中。</p>
</blockquote>
<ul>
<li>根据项目数统计 <code>angular(1.x 、2.x 、4.x、5.x、6.x、7.x)</code>是现在网上使用量最大的框架</li>
<li><code>Angualr</code> 基于 <code>TypeScript</code> 和 <code>react</code>、<code>vue</code> 相比, <code>Angular</code> 更适合中大型企业级项目。</li>
</ul>
<blockquote>
<p>目前 2018 年 11 月 25 日 <code>angular</code> 最新版本 <code>angular7.x</code>。根据官方介绍，<code>Angular</code> 每过几个月 就会更新一个版本。此教程同样适用于后期更新的 <code>Angular8.x</code>、<code>Angular9.x</code> </p>
</blockquote>
<p><img src="https://poetries1.gitee.io/img-repo/20191001/17.png" alt></p>
<p><strong>学习 Angular 必备基础</strong></p>
<blockquote>
<p>必备基础:<code>html</code> 、<code>css</code> 、<code>js</code>、<code>es6</code>、<code>Typescript</code></p>
</blockquote>
<h1 id="二、Angular-环境搭建及创建项目"><a href="#二、Angular-环境搭建及创建项目" class="headerlink" title="二、Angular 环境搭建及创建项目"></a>二、Angular 环境搭建及创建项目</h1><h2 id="2-1-环境搭建"><a href="#2-1-环境搭建" class="headerlink" title="2.1 环境搭建"></a>2.1 环境搭建</h2><p><strong>1. 安装 nodejs</strong></p>
<blockquote>
<p>安装 <code>angular</code> 的计算机上面必须安装最新的 <code>nodejs</code>–注意安装 <code>nodejs</code> 稳定版本</p>
</blockquote>
<p><strong>2. 安装 cnpm</strong></p>
<blockquote>
<p>npm 可能安装失败建议先用 <code>npm</code> 安装一下 <code>cnpm</code> 用淘宝镜像安装<code>https://npm.taobao.org</code></p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">npm install -g cnpm --registry=https://registry.npm.taobao.org</span><br></pre></td></tr></table></figure>
<p><strong>3. 使用 npm/cnpm 命令安装 angular/cli</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">npm install -g @angular/cli </span><br><span class="line"></span><br><span class="line"><span class="comment"># 或者 </span></span><br><span class="line">cnpm install -g @angular/cli</span><br></pre></td></tr></table></figure>
<blockquote>
<p><code>ng v</code> 查看版本信息 </p>
</blockquote>
<p><img src="https://poetries1.gitee.io/img-repo/20191001/18.png" alt></p>
<p><strong>4. 安装插件</strong></p>
<p><img src="https://poetries1.gitee.io/img-repo/20191001/19.png" alt></p>
<p><strong>5. 安装chrome扩展</strong></p>
<blockquote>
<p><a href="https://augury.angular.io/" target="_blank" rel="noopener">https://augury.angular.io/</a></p>
</blockquote>
<blockquote>
<p> 用<code>augury</code>查看<code>component</code>结构，更方便调试</p>
</blockquote>
<p><img src="https://poetries1.gitee.io/img-repo/20191001/20.png" alt></p>
<h2 id="2-2-创建项目"><a href="#2-2-创建项目" class="headerlink" title="2.2 创建项目"></a>2.2 创建项目</h2><figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 创建项目</span></span><br><span class="line">ng new my-app</span><br><span class="line"></span><br><span class="line"><span class="built_in">cd</span> my-app</span><br><span class="line"></span><br><span class="line"><span class="comment"># 运行项目</span></span><br><span class="line">ng serve --open</span><br></pre></td></tr></table></figure>
<h2 id="2-3-目录结构分析"><a href="#2-3-目录结构分析" class="headerlink" title="2.3 目录结构分析"></a>2.3 目录结构分析</h2><p><img src="https://poetries1.gitee.io/img-repo/20191001/21.png" alt></p>
<blockquote>
<p>详情参考 <a href="https://www.angular.cn/guide/file-structure" target="_blank" rel="noopener">https://www.angular.cn/guide/file-structure</a></p>
</blockquote>
<p><strong>app目录（重点）</strong></p>
<blockquote>
<p><code>app</code>目录是我们要编写的代码目录。我们写的代码都是放在这个目录。<br>一个<code>Angular</code>程序至少需要一个模块和一个组件。在我们新建项目的时候命令行已经默认生成出来了</p>
</blockquote>
<p><img src="https://poetries1.gitee.io/img-repo/20191001/22.png" alt></p>
<ul>
<li><code>app.component.ts</code>：这个文件表示组件， </li>
<li>组件是<code>Angular</code>应用的基本构建模块，可以理解为一段带有业务逻辑和数据的<code>Html</code><br>我们来看看<code>app.component.ts</code>中的代码，并解释下代码的意义</li>
</ul>
<p><img src="https://poetries1.gitee.io/img-repo/20191001/23.png" alt></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">/*这里是从Angular核心模块里面引入了component装饰器*/</span></span><br><span class="line"><span class="keyword">import</span> &#123;Component&#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*用装饰器定义了一个组件以及组件的元数据  所有的组件都必须使用这个装饰器来注解*/</span></span><br><span class="line">@Component(&#123;</span><br><span class="line">  <span class="comment">/*组件元数据  Angular会通过这里面的属性来渲染组件并执行逻辑</span></span><br><span class="line"><span class="comment">  * selector就是css选择器，表示这个组件可以通过app-root来调用，index.html中有个&lt;app-root&gt;Loading...&lt;/app-root&gt;标签，这个标签用来展示该组件的内容</span></span><br><span class="line"><span class="comment">  *templateUrl  组件的模板，定义了组件的布局和内容</span></span><br><span class="line"><span class="comment">  *styleUrls   该模板引用那个css样式</span></span><br><span class="line"><span class="comment">  * */</span></span><br><span class="line">  selector: <span class="string">'app-root'</span>,</span><br><span class="line">  templateUrl: <span class="string">'./app.component.html'</span>,</span><br><span class="line">  styleUrls: [<span class="string">'./app.component.css'</span>]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">/*AppComponent本来就是一个普通的typescript类，但是上面的组件元数据装饰器告诉Angular，AppComponent是一个组件，需要把一些元数据附加到这个类上，Angular就会把AppComponent当组件来处理*/</span></span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">AppComponent</span> </span>&#123;</span><br><span class="line">  <span class="comment">/*这个类实际上就是该组件的控制器，我们的业务逻辑就是在这个类中编写*/</span></span><br><span class="line">  title = <span class="string">'学习Angular'</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>组件相关的概念</strong></p>
<ol>
<li>组件元数据装饰器（<code>@Component</code>）<br>简称组件装饰器，用来告知<code>Angular</code>框架如何处理一个<code>TypeScript</code>类.<br><code>Component</code>装饰器包含多个属性，这些属性的值叫做元数据，<code>Angular</code>会根据这些元数据的值来渲染组件并执行组件的逻辑</li>
<li>模板（<code>Template</code>）<br>我们可以通过组件自带的模板来定义组件的外观，模板以<code>html</code>的形式存在，告诉<code>Angular</code>如何来渲染组件，一般来说，模板看起来很像<code>html</code>，但是我们可以在模板中使用<code>Angular</code>的数据绑定语法，来呈现控制器中的数据。</li>
<li>控制器（<code>controller</code>）<br>控制器就是一个普通的<code>typescript</code>类，他会被<code>@Component</code>来装饰，控制器会包含组件所有的属性和方法，绝大多数的业务逻辑都是写在控制器里的。控制器通过数据绑定与模板来通讯，模板展现控制器的数据，控制器处理模板上发生的事件。</li>
</ol>
<p><strong>装饰器</strong>，模板和控制器是组件的必备要素。还有一些可选的元素，比如：</p>
<ul>
<li>输入属性（<code>@inputs</code>）:是用来接收外部传入的数据的,<code>Angular</code>的程序结构就是一个组件树，输入属性允许在组件树种传递数据<br>提供器（<code>providers</code>）：这个是用来做依赖注入的 </li>
<li>生命周期钩子（<code>LifeCycle Hooks</code>）：一个组件从创建到销毁的过程中会有多个钩子会被触发，类似于Android中的<code>Activity</code>的生命周期 </li>
<li>样式表：组件可以关联一些样式表 </li>
<li>动画（<code>Animations</code>）： <code>Angular</code>提供了一个动画包来帮助我们方便的创建一些跟组件相关的动画效果，比如淡入淡出等 </li>
<li>输出属性（<code>@Outputs</code>）：用来定义一些其他组件可能需要的事件或者用来在组件之间共享数据</li>
</ul>
<blockquote>
<p>组件的中关系就如下图所示</p>
</blockquote>
<p><img src="https://poetries1.gitee.io/img-repo/20191001/24.png" alt></p>
<p>下面我们来看看模块文件 </p>
<ul>
<li><code>app.module.ts</code>：这个文件表示模块</li>
<li>与<code>AppComponent</code>类似，模块也需要装饰器来装饰</li>
</ul>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; BrowserModule &#125; <span class="keyword">from</span> <span class="string">'@angular/platform-browser'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; NgModule &#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> &#123; AppRoutingModule &#125; <span class="keyword">from</span> <span class="string">'./app-routing.module'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; AppComponent &#125; <span class="keyword">from</span> <span class="string">'./app.component'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; HeroesComponent &#125; <span class="keyword">from</span> <span class="string">'./heroes/heroes.component'</span>;</span><br><span class="line"></span><br><span class="line">@NgModule(&#123;</span><br><span class="line">  declarations: [</span><br><span class="line">   <span class="comment">// 声明模块里有什么东西 只能声明：组件/指令/管道</span></span><br><span class="line">    AppComponent,</span><br><span class="line">    HeroesComponent</span><br><span class="line">  ],</span><br><span class="line">  <span class="comment">// 声明该模块所依赖的模块</span></span><br><span class="line">  imports: [</span><br><span class="line">    BrowserModule,</span><br><span class="line">    AppRoutingModule</span><br><span class="line">  ],</span><br><span class="line">  <span class="comment">// 默认情况下是空的</span></span><br><span class="line">  providers: [],</span><br><span class="line">  <span class="comment">// 声明模块的主组件是什么</span></span><br><span class="line">  bootstrap: [AppComponent]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">AppModule</span> </span>&#123; &#125;</span><br></pre></td></tr></table></figure>
<h2 id="2-4-Angular-cli"><a href="#2-4-Angular-cli" class="headerlink" title="2.4 Angular cli"></a>2.4 Angular cli</h2><blockquote>
<p><a href="https://cli.angular.io" target="_blank" rel="noopener">https://cli.angular.io</a></p>
</blockquote>
<blockquote>
<p>通过<code>ng g</code>列出当前命令</p>
</blockquote>
<p><img src="https://poetries1.gitee.io/img-repo/20191001/25.png" alt></p>
<p><strong>1. 创建新组件 <code>ng generate component component-name</code></strong></p>
<blockquote>
<p><code>ng g component components/header</code> 指定生成到哪个目录</p>
</blockquote>
<p>该命令会把生成的组件，添加到 <code>src/app/app.module.ts</code> 文件中 <code>@NgModule</code> 的 <code>declarations</code> 列表中声明</p>
<p><img src="https://poetries1.gitee.io/img-repo/20191001/26.png" alt></p>
<p><strong>2. 使用 Angular CLI 创建一个名叫 hero 的服务</strong></p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">ng generate service hero</span><br></pre></td></tr></table></figure>
<blockquote>
<p>该命令会在 <code>src/app/hero.service.ts</code> 中生成 <code>HeroService</code> 类的骨架。 <code>HeroService</code> 类的代码如下：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Injectable &#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br><span class="line"></span><br><span class="line">@Injectable(&#123;</span><br><span class="line">  providedIn: <span class="string">'root'</span>,</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">HeroService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">constructor</span>() &#123; &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>3. 添加 AppRoutingModule</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">ng generate <span class="built_in">module</span> app-routing --flat --<span class="built_in">module</span>=app</span><br></pre></td></tr></table></figure>
<ul>
<li><code>--flat</code> 把这个文件放进了 <code>src/app</code> 中，而不是单独的目录中。</li>
<li><code>--module=app</code> 告诉 <code>CLI</code> 把它注册到 <code>AppModule</code>的 <code>imports</code> 数组中。</li>
</ul>
<p>生成的文件是这样的：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">src/app/app-routing.module.ts (generated)</span><br><span class="line">content_copy</span><br><span class="line"><span class="keyword">import</span> &#123; NgModule &#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; CommonModule &#125; <span class="keyword">from</span> <span class="string">'@angular/common'</span>;</span><br><span class="line"></span><br><span class="line">@NgModule(&#123;</span><br><span class="line">  imports: [</span><br><span class="line">    CommonModule</span><br><span class="line">  ],</span><br><span class="line">  declarations: []</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">AppRoutingModule</span> </span>&#123; &#125;</span><br></pre></td></tr></table></figure>
<p>修改后</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; NgModule &#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; Routes, RouterModule &#125; <span class="keyword">from</span> <span class="string">'@angular/router'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> routes: Routes = [];</span><br><span class="line"></span><br><span class="line">@NgModule(&#123;</span><br><span class="line">  imports: [RouterModule.forRoot(routes)],</span><br><span class="line">  exports: [RouterModule]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">AppRoutingModule</span> </span>&#123; &#125;</span><br></pre></td></tr></table></figure>
<h1 id="三、angular组件及组件里的模板"><a href="#三、angular组件及组件里的模板" class="headerlink" title="三、angular组件及组件里的模板"></a>三、angular组件及组件里的模板</h1><h2 id="3-1-创建angualr组件"><a href="#3-1-创建angualr组件" class="headerlink" title="3.1 创建angualr组件"></a>3.1 创建angualr组件</h2><p><strong>1. 创建组件</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">ng g component components/header</span><br></pre></td></tr></table></figure>
<p><strong>2. 使用组件</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">app-header</span>&gt;</span><span class="tag">&lt;/<span class="name">app-header</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="3-2-Angular-绑定数据"><a href="#3-2-Angular-绑定数据" class="headerlink" title="3.2 Angular 绑定数据"></a>3.2 Angular 绑定数据</h2><p><strong>1. 数据文本绑定</strong></p>
<blockquote>
<p>定义数据几种方式</p>
</blockquote>
<p><img src="https://poetries1.gitee.io/img-repo/20191001/27.png" alt></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">h1</span>&gt;</span>&#123;&#123;title&#125;&#125;<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>2. 绑定<code>HTML</code></strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">this</span>.h=<span class="string">"&lt;h2&gt;这是一个 h2 用[innerHTML]来解析&lt;/h2&gt;"</span></span><br></pre></td></tr></table></figure>
 <figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> [<span class="attr">innerHTML</span>]=<span class="string">"h"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="3-3-声明属性的几种方式"><a href="#3-3-声明属性的几种方式" class="headerlink" title="3.3 声明属性的几种方式"></a>3.3 声明属性的几种方式</h2><ul>
<li><code>public</code> 共有（默认） 可以在类里外使用</li>
<li><code>protected</code> 保护类型 只能在当前类和子类中使用</li>
<li><code>private</code> 私有类型 只能在当期类使用</li>
</ul>
<h2 id="3-4-绑定属性"><a href="#3-4-绑定属性" class="headerlink" title="3.4 绑定属性"></a>3.4 绑定属性</h2><blockquote>
<p>用<code>[]</code>包裹</p>
</blockquote>
 <figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> [<span class="attr">id</span>]=<span class="string">"id"</span> [<span class="attr">title</span>]=<span class="string">"msg"</span>&gt;</span>调试工具看看我的属性<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p> <img src="https://poetries1.gitee.io/img-repo/20191001/28.png" alt></p>
<h2 id="3-5-数据循环-ngFor"><a href="#3-5-数据循环-ngFor" class="headerlink" title="3.5 数据循环 *ngFor"></a>3.5 数据循环 *ngFor</h2><p><strong>1. *ngFor 普通循环</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">HomeComponent</span> <span class="title">implements</span> <span class="title">OnInit</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  arr = [&#123; <span class="attr">name</span>: <span class="string">'poetries'</span>, <span class="attr">age</span>: <span class="number">22</span> &#125;, &#123; <span class="attr">name</span>: <span class="string">'jing'</span> , <span class="attr">age</span>: <span class="number">31</span>&#125;];</span><br><span class="line">  <span class="keyword">constructor</span>() &#123; &#125;</span><br><span class="line"></span><br><span class="line">  ngOnInit() &#123;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">ul</span> *<span class="attr">ngIf</span>=<span class="string">"arr.length&gt;0"</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">li</span> *<span class="attr">ngFor</span>=<span class="string">"let item of arr"</span>&gt;</span>&#123;&#123;item.name&#125;&#125;- &#123;&#123;item.age&#125;&#125;<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>2. 循环的时候设置 key</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">ul</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">li</span> *<span class="attr">ngFor</span>=<span class="string">"let item of list;let i = index;"</span>&gt;</span> <span class="comment">&lt;!-- 把索引index赋给i --&gt;</span></span><br><span class="line">     &#123;&#123;item&#125;&#125; --&#123;&#123;i&#125;&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">li</span>&gt;</span> <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>3. template 循环数据</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">ul</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">li</span> <span class="attr">template</span>=<span class="string">"ngFor let item of list"</span>&gt;</span></span><br><span class="line">&#123;&#123;item&#125;&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">li</span>&gt;</span> <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="3-6-条件判断-ngIf"><a href="#3-6-条件判断-ngIf" class="headerlink" title="3.6 条件判断 *ngIf"></a>3.6 条件判断 *ngIf</h2><figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">p</span> *<span class="attr">ngIf</span>=<span class="string">"list.length &gt; 3"</span>&gt;</span>这是 ngIF 判断是否显示<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">p</span> <span class="attr">template</span>=<span class="string">"ngIf list.length &gt; 3"</span>&gt;</span>这是 ngIF 判断是否显示<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="3-7-ngSwitch"><a href="#3-7-ngSwitch" class="headerlink" title="3.7 *ngSwitch"></a>3.7 *ngSwitch</h2><figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">ul</span> [<span class="attr">ngSwitch</span>]=<span class="string">"score"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">li</span> *<span class="attr">ngSwitchCase</span>=<span class="string">"1"</span>&gt;</span>已支付<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">li</span> *<span class="attr">ngSwitchCase</span>=<span class="string">"2"</span>&gt;</span>订单已经确认<span class="tag">&lt;/<span class="name">li</span>&gt;</span> <span class="tag">&lt;<span class="name">li</span> *<span class="attr">ngSwitchCase</span>=<span class="string">"3"</span>&gt;</span>已发货<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">li</span> *<span class="attr">ngSwitchDefault</span>&gt;</span>无效<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="3-8-执行事件-click-”getData-”"><a href="#3-8-执行事件-click-”getData-”" class="headerlink" title="3.8 执行事件 (click)=”getData()”"></a>3.8 执行事件 (click)=”getData()”</h2><figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">"button"</span> (<span class="attr">click</span>)=<span class="string">"getData()"</span>&gt;</span> 点击按钮触发事件</span><br><span class="line"><span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">"button"</span> (<span class="attr">click</span>)=<span class="string">"setData()"</span>&gt;</span> 点击按钮设置数据</span><br><span class="line"><span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">getData()&#123; <span class="comment">/*自定义方法获取数据*/</span> <span class="comment">//获取</span></span><br><span class="line">  alert(<span class="keyword">this</span>.msg);</span><br><span class="line">&#125; </span><br><span class="line">setData()&#123;</span><br><span class="line">    <span class="comment">//设置值</span></span><br><span class="line">    <span class="keyword">this</span>.msg=<span class="string">'这是设置的值'</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="3-9-表单事件"><a href="#3-9-表单事件" class="headerlink" title="3.9 表单事件"></a>3.9 表单事件</h2><figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">input</span></span></span><br><span class="line"><span class="tag"><span class="attr">type</span>=<span class="string">"text"</span></span></span><br><span class="line"><span class="tag">(<span class="attr">keyup</span>)=<span class="string">"keyUpFn($event)"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> (<span class="attr">keyup</span>)=<span class="string">"keyUpFn($event)"</span>/&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">keyUpFn(e)&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(e)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="3-10-双向数据绑定"><a href="#3-10-双向数据绑定" class="headerlink" title="3.10 双向数据绑定"></a>3.10 双向数据绑定</h2><figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">input</span> [(<span class="attr">ngModel</span>)]=<span class="string">"inputVal"</span>&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>注意引入:<code>FormsModule</code></p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;FormsModule&#125; <span class="keyword">from</span> <span class="string">'@angular/forms'</span></span><br><span class="line"></span><br><span class="line">NgModule(&#123;</span><br><span class="line">  declarations: [</span><br><span class="line">    AppComponent,</span><br><span class="line">    HeaderComponent,</span><br><span class="line">    FooterComponent,</span><br><span class="line">    NewsComponent</span><br><span class="line">  ], </span><br><span class="line">  imports: [</span><br><span class="line">    BrowserModule,</span><br><span class="line">    FormsModule</span><br><span class="line">  ],</span><br><span class="line">  providers: [],</span><br><span class="line">  bootstrap: [AppComponent]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">AppModule</span> </span>&#123; &#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--使用--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> [(<span class="attr">ngModel</span>)]=<span class="string">"inputValue"</span>/&gt;</span> &#123;&#123;inputValue&#125;&#125;</span><br></pre></td></tr></table></figure>
<h2 id="3-11-ngClass-、-ngStyle"><a href="#3-11-ngClass-、-ngStyle" class="headerlink" title="3. 11 [ngClass]、[ngStyle]"></a>3. 11 [ngClass]、[ngStyle]</h2><p><strong>1. [ngClass]:</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> [<span class="attr">ngClass</span>]=<span class="string">"&#123;'red': true, 'blue': false&#125;"</span>&gt;</span> </span><br><span class="line">    这是一个 div</span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">public flag=<span class="literal">false</span>;</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> [<span class="attr">ngClass</span>]=<span class="string">"&#123;'red': flag, 'blue': !flag&#125;"</span>&gt;</span></span><br><span class="line">这是一个 div <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">public arr = [<span class="number">1</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>];</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">ul</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">li</span> *<span class="attr">ngFor</span>=<span class="string">"let item of arr, let i = index"</span>&gt;</span> <span class="tag">&lt;<span class="name">span</span> [<span class="attr">ngClass</span>]=<span class="string">"&#123;'red': i==0&#125;"</span>&gt;</span>&#123;&#123;item&#125;&#125;<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">li</span>&gt;</span> <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>2. [ngStyle]:</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> [<span class="attr">ngStyle</span>]=<span class="string">"&#123;'background-color':'green'&#125;"</span>&gt;</span>你好 ngStyle<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">public attr=<span class="string">'red'</span>;</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> [<span class="attr">ngStyle</span>]=<span class="string">"&#123;'background-color':attr&#125;"</span>&gt;</span>你好 ngStyle<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="3-12-管道"><a href="#3-12-管道" class="headerlink" title="3.12 管道"></a>3.12 管道</h2><figure class="highlight js"><table><tr><td class="code"><pre><span class="line">public today=<span class="keyword">new</span> <span class="built_in">Date</span>();</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;&#123;today | date:'yyyy-MM-dd HH:mm:ss' &#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>其他管道</strong></p>
<blockquote>
<p><code>angular</code>中的管道(<code>pipe</code>)是用来对输入的数据进行处理，如大小写转换、数值和日期格式化等</p>
</blockquote>
<blockquote>
<p><code>angular</code>中的管道(<code>pipe</code>) 以及自定义管道适用于<code>angular4 angualr5 angualr6 angular7</code></p>
</blockquote>
<p>常用的管道（<code>pipe</code>）有</p>
<p><strong>1. 大小写转换</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--转换成大写--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;&#123;str | uppercase&#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!--转换成小写--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;&#123;str | lowercase&#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>2. 日期格式转换</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">p</span>&gt;</span></span><br><span class="line">&#123;&#123;today | date:'yyyy-MM-dd HH:mm:ss' &#125;&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>3. 小数位数</strong></p>
<blockquote>
<p>接收的参数格式为<code>{最少整数位数}.{最少小数位数}-{最多小数位数}</code></p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--保留2~4位小数--&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;&#123;p | number:'1.2-4'&#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>4. JavaScript 对象序列化</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">p</span>&gt;</span></span><br><span class="line">    &#123;&#123; &#123; name: 'semlinker' &#125; | json &#125;&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">p</span>&gt;</span> </span><br><span class="line"><span class="comment">&lt;!-- Output: &#123; "name": "semlinker" &#125; --&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>5. slice</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;&#123; 'semlinker' | slice:0:3 &#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span> </span><br><span class="line"><span class="comment">&lt;!-- Output: sem --&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>6. 管道链</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">p</span>&gt;</span></span><br><span class="line">&#123;&#123; 'semlinker' | slice:0:3 | uppercase &#125;&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">p</span>&gt;</span> </span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- Output: SEM --&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>7. 自定义管道</strong></p>
<p>自定义管道的步骤：</p>
<ul>
<li>使用 <code>@Pipe</code> 装饰器定义 <code>Pipe</code> 的 <code>metadata</code> 信息，如 <code>Pipe</code> 的名称 - 即 <code>name</code> 属性</li>
<li>实现 <code>PipeTransform</code> 接口中定义的 <code>transform</code> 方法</li>
</ul>
<p><strong>7.1 WelcomePipe 定义</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Pipe, PipeTransform &#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br><span class="line"></span><br><span class="line">[@Pipe](<span class="regexp">/user/</span>Pipe)(&#123; <span class="attr">name</span>: <span class="string">'welcome'</span> &#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">WelcomePipe</span> <span class="title">implements</span> <span class="title">PipeTransform</span> </span>&#123;</span><br><span class="line">  transform(value: string): string &#123;</span><br><span class="line">    <span class="keyword">if</span>(!value) <span class="keyword">return</span> value;</span><br><span class="line">    <span class="keyword">if</span>(<span class="keyword">typeof</span> value !== <span class="string">'string'</span>) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'Invalid pipe argument for WelcomePipe'</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">"Welcome to "</span> + value;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>7.2 WelcomePipe 使用</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">p</span> <span class="attr">ngNonBindable</span>&gt;</span>&#123;&#123; 'semlinker' | welcome &#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;&#123; 'semlinker' | welcome &#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span> <span class="comment">&lt;!-- Output: Welcome to semlinker --&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>7.3 RepeatPipe 定义</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;Pipe, PipeTransform&#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br><span class="line"></span><br><span class="line">[@Pipe](<span class="regexp">/user/</span>Pipe)(&#123;<span class="attr">name</span>: <span class="string">'repeat'</span>&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">RepeatPipe</span> <span class="title">implements</span> <span class="title">PipeTransform</span> </span>&#123;</span><br><span class="line">    transform(value: any, <span class="attr">times</span>: number) &#123;</span><br><span class="line">        <span class="keyword">return</span> value.repeat(times);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>7.4 RepeatPipe 使用</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">p</span> <span class="attr">ngNonBindable</span>&gt;</span></span><br><span class="line">   &#123;&#123; 'lo' | repeat:3 &#125;&#125;</span><br><span class="line">   <span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">p</span>&gt;</span></span><br><span class="line">    &#123;&#123; 'lo' | repeat:3 &#125;&#125;</span><br><span class="line">   <span class="tag">&lt;/<span class="name">p</span>&gt;</span> </span><br><span class="line">   <span class="comment">&lt;!-- Output: lololo --&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="3-13-实现一个人员登记表单-案例"><a href="#3-13-实现一个人员登记表单-案例" class="headerlink" title="3.13 实现一个人员登记表单-案例"></a>3.13 实现一个人员登记表单-案例</h2><p> <img src="https://poetries1.gitee.io/img-repo/20191001/29.png" alt></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 创建组件</span></span><br><span class="line">ng g component components/form</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Component, OnInit &#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br><span class="line"></span><br><span class="line">@Component(&#123;</span><br><span class="line">  selector: <span class="string">'app-form'</span>,</span><br><span class="line">  templateUrl: <span class="string">'./form.component.html'</span>,</span><br><span class="line">  styleUrls: [<span class="string">'./form.component.scss'</span>]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">FormComponent</span> <span class="title">implements</span> <span class="title">OnInit</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  public peopleInfo:any = &#123;</span><br><span class="line">    username: <span class="string">''</span>,</span><br><span class="line">    sex: <span class="string">'2'</span>,</span><br><span class="line">    cityList: [<span class="string">'北京'</span>, <span class="string">'上海'</span>, <span class="string">'深圳'</span>],</span><br><span class="line">    city: <span class="string">'上海'</span>,</span><br><span class="line"></span><br><span class="line">    hobby:[&#123;</span><br><span class="line">          title: <span class="string">'吃饭'</span>,</span><br><span class="line">          checked:<span class="literal">false</span></span><br><span class="line">      &#125;,&#123;</span><br><span class="line">            title:<span class="string">'睡觉'</span>,</span><br><span class="line">            checked:<span class="literal">false</span></span><br><span class="line">        &#125;,&#123;</span><br><span class="line"></span><br><span class="line">          title:<span class="string">'敲代码'</span>,</span><br><span class="line">          checked:<span class="literal">true</span></span><br><span class="line">      &#125;],</span><br><span class="line"></span><br><span class="line">      mark:<span class="string">''</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">constructor</span>() &#123; &#125;</span><br><span class="line"></span><br><span class="line">  ngOnInit() &#123;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line">  doSubmit()&#123;</span><br><span class="line">    <span class="comment">/*    </span></span><br><span class="line"><span class="comment">    jquery  dom操作</span></span><br><span class="line"><span class="comment">      &lt;input type="text" id="username" /&gt;</span></span><br><span class="line"><span class="comment">      let usernameDom:any=document.getElementById('username');</span></span><br><span class="line"><span class="comment">      console.log(usernameDom.value);    </span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line"></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span>.peopleInfo);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">h2</span>&gt;</span>人员登记系统<span class="tag">&lt;/<span class="name">h2</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"people_list"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">ul</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">li</span>&gt;</span>姓 名：<span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">id</span>=<span class="string">"username"</span> [(<span class="attr">ngModel</span>)]=<span class="string">"peopleInfo.username"</span> <span class="attr">value</span>=<span class="string">"fonm_input"</span> /&gt;</span><span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">li</span>&gt;</span>性 别：</span><br><span class="line">      <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"radio"</span> <span class="attr">value</span>=<span class="string">"1"</span> <span class="attr">name</span>=<span class="string">"sex"</span> <span class="attr">id</span>=<span class="string">"sex1"</span> [(<span class="attr">ngModel</span>)]=<span class="string">"peopleInfo.sex"</span>&gt;</span> <span class="tag">&lt;<span class="name">label</span> <span class="attr">for</span>=<span class="string">"sex1"</span>&gt;</span>男 <span class="tag">&lt;/<span class="name">label</span>&gt;</span>　　　</span><br><span class="line">      <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"radio"</span> <span class="attr">value</span>=<span class="string">"2"</span> <span class="attr">name</span>=<span class="string">"sex"</span>  <span class="attr">id</span>=<span class="string">"sex2"</span> [(<span class="attr">ngModel</span>)]=<span class="string">"peopleInfo.sex"</span>&gt;</span> <span class="tag">&lt;<span class="name">label</span> <span class="attr">for</span>=<span class="string">"sex2"</span>&gt;</span>女 <span class="tag">&lt;/<span class="name">label</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">li</span>&gt;</span></span><br><span class="line">    城 市：</span><br><span class="line">      <span class="tag">&lt;<span class="name">select</span> <span class="attr">name</span>=<span class="string">"city"</span> <span class="attr">id</span>=<span class="string">"city"</span> [(<span class="attr">ngModel</span>)]=<span class="string">"peopleInfo.city"</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">option</span> [<span class="attr">value</span>]=<span class="string">"item"</span> *<span class="attr">ngFor</span>=<span class="string">"let item of peopleInfo.cityList"</span>&gt;</span>&#123;&#123;item&#125;&#125;<span class="tag">&lt;/<span class="name">option</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">li</span>&gt;</span></span><br><span class="line">        爱 好：</span><br><span class="line">        <span class="tag">&lt;<span class="name">span</span> *<span class="attr">ngFor</span>=<span class="string">"let item of peopleInfo.hobby;let key=index;"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"checkbox"</span>  [<span class="attr">id</span>]=<span class="string">"'check'+key"</span> [(<span class="attr">ngModel</span>)]=<span class="string">"item.checked"</span>/&gt;</span> <span class="tag">&lt;<span class="name">label</span> [<span class="attr">for</span>]=<span class="string">"'check'+key"</span>&gt;</span> &#123;&#123;item.title&#125;&#125;<span class="tag">&lt;/<span class="name">label</span>&gt;</span></span><br><span class="line">            <span class="symbol">&amp;nbsp;</span><span class="symbol">&amp;nbsp;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">li</span>&gt;</span></span><br><span class="line">       备 注：</span><br><span class="line">       <span class="tag">&lt;<span class="name">textarea</span> <span class="attr">name</span>=<span class="string">"mark"</span> <span class="attr">id</span>=<span class="string">"mark"</span> <span class="attr">cols</span>=<span class="string">"30"</span> <span class="attr">rows</span>=<span class="string">"10"</span> [(<span class="attr">ngModel</span>)]=<span class="string">"peopleInfo.mark"</span>&gt;</span><span class="tag">&lt;/<span class="name">textarea</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line"></span><br><span class="line">  <span class="tag">&lt;<span class="name">button</span> (<span class="attr">click</span>)=<span class="string">"doSubmit()"</span> <span class="attr">class</span>=<span class="string">"submit"</span>&gt;</span>获取表单的内容<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line"></span><br><span class="line">  <span class="tag">&lt;<span class="name">pre</span>&gt;</span></span><br><span class="line">    &#123;&#123;peopleInfo | json&#125;&#125;</span><br><span class="line">  <span class="tag">&lt;/<span class="name">pre</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight scss"><table><tr><td class="code"><pre><span class="line"><span class="selector-tag">h2</span>&#123;</span><br><span class="line">    <span class="attribute">text-align</span>: center;</span><br><span class="line">&#125;</span><br><span class="line"><span class="selector-class">.people_list</span>&#123;</span><br><span class="line">    <span class="attribute">width</span>: <span class="number">400px</span>;</span><br><span class="line">    <span class="attribute">margin</span>: <span class="number">40px</span> auto;</span><br><span class="line">    <span class="attribute">padding</span>:<span class="number">20px</span>;</span><br><span class="line">    <span class="attribute">border</span>:<span class="number">1px</span> solid <span class="number">#eee</span>;</span><br><span class="line">    <span class="selector-tag">li</span>&#123;</span><br><span class="line">        <span class="attribute">height</span>: <span class="number">50px</span>;</span><br><span class="line">        <span class="attribute">line-height</span>: <span class="number">50px</span>;</span><br><span class="line">        <span class="selector-class">.fonm_input</span>&#123;</span><br><span class="line">            <span class="attribute">width</span>: <span class="number">300px</span>;</span><br><span class="line">            <span class="attribute">height</span>: <span class="number">28px</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="selector-class">.submit</span>&#123;</span><br><span class="line">        <span class="attribute">width</span>: <span class="number">100px</span>;</span><br><span class="line">        <span class="attribute">height</span>: <span class="number">30px</span>;</span><br><span class="line">        <span class="attribute">float</span>: right;</span><br><span class="line">        <span class="attribute">margin-right</span>: <span class="number">50px</span>;</span><br><span class="line">        <span class="attribute">margin-top</span>:<span class="number">120px</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="3-14-实现一个完整的ToDo-案例"><a href="#3-14-实现一个完整的ToDo-案例" class="headerlink" title="3.14 实现一个完整的ToDo-案例"></a>3.14 实现一个完整的ToDo-案例</h2><p> <img src="https://poetries1.gitee.io/img-repo/20191001/30.png" alt></p>
<p><strong>基础版</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 创建组件</span></span><br><span class="line">ng g component components/todo</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">h2</span>&gt;</span>todoList<span class="tag">&lt;/<span class="name">h2</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"todolist"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">"form_input"</span> <span class="attr">type</span>=<span class="string">"text"</span> [(<span class="attr">ngModel</span>)]=<span class="string">"keyword"</span> (<span class="attr">keyup</span>)=<span class="string">"doAdd($event)"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">hr</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">h3</span>&gt;</span>待办事项<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">ul</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">li</span> *<span class="attr">ngFor</span>=<span class="string">"let item of todolist;let key=index;"</span> [<span class="attr">hidden</span>]=<span class="string">"item.status==1"</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"checkbox"</span> [(<span class="attr">ngModel</span>)]=<span class="string">"item.status"</span> /&gt;</span>  &#123;&#123;item.title&#125;&#125;   ------ <span class="tag">&lt;<span class="name">button</span> (<span class="attr">click</span>)=<span class="string">"deleteData(key)"</span>&gt;</span>X<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">h3</span>&gt;</span>已完成事项<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">ul</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">li</span> *<span class="attr">ngFor</span>=<span class="string">"let item of todolist;let key=index;"</span> [<span class="attr">hidden</span>]=<span class="string">"item.status==0"</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"checkbox"</span> [(<span class="attr">ngModel</span>)]=<span class="string">"item.status"</span> /&gt;</span>  &#123;&#123;item.title&#125;&#125;   ------ <span class="tag">&lt;<span class="name">button</span> (<span class="attr">click</span>)=<span class="string">"deleteData(key)"</span>&gt;</span>X<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Component, OnInit &#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br><span class="line"></span><br><span class="line">@Component(&#123;</span><br><span class="line">  selector: <span class="string">'app-todo'</span>,</span><br><span class="line">  templateUrl: <span class="string">'./todo.component.html'</span>,</span><br><span class="line">  styleUrls: [<span class="string">'./todo.component.scss'</span>]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">TodoComponent</span> <span class="title">implements</span> <span class="title">OnInit</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  public keyword: string;</span><br><span class="line"></span><br><span class="line">  public todolist: any[] = [];</span><br><span class="line"></span><br><span class="line">  <span class="keyword">constructor</span>() &#123; &#125;</span><br><span class="line"></span><br><span class="line">  ngOnInit() &#123;</span><br><span class="line">  &#125;</span><br><span class="line">  doAdd(e)&#123;</span><br><span class="line">    <span class="keyword">if</span>(e.keyCode == <span class="number">13</span>)&#123;</span><br><span class="line">        <span class="keyword">if</span>(!<span class="keyword">this</span>.todolistHasKeyword(<span class="keyword">this</span>.todolist, <span class="keyword">this</span>.keyword))&#123;</span><br><span class="line">          <span class="keyword">this</span>.todolist.push(&#123;</span><br><span class="line">            title: <span class="keyword">this</span>.keyword,</span><br><span class="line">            status: <span class="number">0</span>                   <span class="comment">//0表示代办事项  1表示已完成事项</span></span><br><span class="line">          &#125;);</span><br><span class="line">          <span class="keyword">this</span>.keyword=<span class="string">''</span>;</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">          alert(<span class="string">'数据已经存在'</span>);</span><br><span class="line">          <span class="keyword">this</span>.keyword=<span class="string">''</span>;</span><br><span class="line">        &#125;</span><br><span class="line">     &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  deleteData(key)&#123;</span><br><span class="line">    <span class="keyword">this</span>.todolist.splice(key,<span class="number">1</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  <span class="comment">//如果数组里面有keyword返回true  否则返回false</span></span><br><span class="line">  todolistHasKeyword(todolist:any, <span class="attr">keyword</span>:any)&#123;</span><br><span class="line">    <span class="comment">//异步  会存在问题</span></span><br><span class="line">    <span class="comment">// todolist.forEach(value =&gt; &#123;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//   if(value.title==keyword)&#123;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//       return true;</span></span><br><span class="line">    <span class="comment">//   &#125; </span></span><br><span class="line">    <span class="comment">// &#125;);</span></span><br><span class="line">    <span class="keyword">if</span>(!keyword)  <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span>; i&lt;todolist.length; i++)&#123;</span><br><span class="line">      <span class="keyword">if</span>(todolist[i].title==keyword)&#123;</span><br><span class="line">          <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">      &#125; </span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight scss"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="selector-tag">h2</span>&#123;</span><br><span class="line">    <span class="attribute">text-align</span>: center;</span><br><span class="line">&#125;</span><br><span class="line"><span class="selector-class">.todolist</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="attribute">width</span>: <span class="number">400px</span>;</span><br><span class="line">    <span class="attribute">margin</span>: <span class="number">20px</span> auto;</span><br><span class="line">    <span class="selector-class">.form_input</span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="attribute">margin-bottom</span>: <span class="number">20px</span>;</span><br><span class="line"></span><br><span class="line">        <span class="attribute">width</span>: <span class="number">300px</span>;</span><br><span class="line">        <span class="attribute">height</span>: <span class="number">32px</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="selector-tag">li</span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="attribute">line-height</span>: <span class="number">60px</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="3-15-搜索缓存数据-案例"><a href="#3-15-搜索缓存数据-案例" class="headerlink" title="3.15 搜索缓存数据-案例"></a>3.15 搜索缓存数据-案例</h2><p><strong>基础版</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 创建组件</span></span><br><span class="line">ng g component components/search</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"search"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> [(<span class="attr">ngModel</span>)]=<span class="string">"keyword"</span> /&gt;</span>  <span class="tag">&lt;<span class="name">button</span> (<span class="attr">click</span>)=<span class="string">"doSearch()"</span>&gt;</span>搜索<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">hr</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">ul</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">li</span> *<span class="attr">ngFor</span>=<span class="string">"let item of historyList;let key=index;"</span>&gt;</span>&#123;&#123;item&#125;&#125;   ------ <span class="tag">&lt;<span class="name">button</span> (<span class="attr">click</span>)=<span class="string">"deleteHistroy(key)"</span>&gt;</span>X<span class="tag">&lt;/<span class="name">button</span>&gt;</span><span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Component, OnInit &#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br><span class="line"></span><br><span class="line">@Component(&#123;</span><br><span class="line">  selector: <span class="string">'app-search'</span>,</span><br><span class="line">  templateUrl: <span class="string">'./search.component.html'</span>,</span><br><span class="line">  styleUrls: [<span class="string">'./search.component.scss'</span>]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">SearchComponent</span> <span class="title">implements</span> <span class="title">OnInit</span> </span>&#123;</span><br><span class="line">  public keyword: string;</span><br><span class="line">  public historyList: any[] = [];</span><br><span class="line"></span><br><span class="line">  <span class="keyword">constructor</span>() &#123; &#125;</span><br><span class="line">  ngOnInit() &#123;</span><br><span class="line">  &#125;</span><br><span class="line">  doSearch()&#123;</span><br><span class="line">    <span class="keyword">if</span>(<span class="keyword">this</span>.historyList.indexOf(<span class="keyword">this</span>.keyword)==<span class="number">-1</span>)&#123;</span><br><span class="line">      <span class="keyword">this</span>.historyList.push(<span class="keyword">this</span>.keyword);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">this</span>.keyword = <span class="string">''</span>;    </span><br><span class="line">  &#125;</span><br><span class="line">  deleteHistroy(key)&#123;</span><br><span class="line">      alert(key);</span><br><span class="line">      <span class="keyword">this</span>.historyList.splice(key,<span class="number">1</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight scss"><table><tr><td class="code"><pre><span class="line"><span class="selector-class">.search</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="attribute">width</span>: <span class="number">400px</span>;</span><br><span class="line">    <span class="attribute">margin</span>: <span class="number">20px</span> auto;</span><br><span class="line">    <span class="selector-tag">input</span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="attribute">margin-bottom</span>: <span class="number">20px</span>;</span><br><span class="line"></span><br><span class="line">        <span class="attribute">width</span>: <span class="number">300px</span>;</span><br><span class="line">        <span class="attribute">height</span>: <span class="number">32px</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="selector-tag">button</span>&#123;</span><br><span class="line">        <span class="attribute">height</span>: <span class="number">32px</span>;</span><br><span class="line">        <span class="attribute">width</span>: <span class="number">80px</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="四、Angular-中的服务"><a href="#四、Angular-中的服务" class="headerlink" title="四、Angular 中的服务"></a>四、Angular 中的服务</h1><h2 id="4-1-服务"><a href="#4-1-服务" class="headerlink" title="4.1 服务"></a>4.1 服务</h2><blockquote>
<p>定义公共的方法，使得方法在组件之间共享调用</p>
</blockquote>
<p> <img src="https://poetries1.gitee.io/img-repo/20191001/31.png" alt></p>
<p><strong>1. 创建服务命令</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">ng g service my-new-service</span><br><span class="line"></span><br><span class="line"><span class="comment"># 创建到指定目录下面</span></span><br><span class="line">ng g service services/storage</span><br></pre></td></tr></table></figure>
<p><strong>2. app.module.ts 里面引入创建的服务</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// app.module.ts 里面引入创建的服务</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> &#123; StorageService &#125; <span class="keyword">from</span> <span class="string">'./services/storage.service'</span>;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// NgModule 里面的 providers 里面依赖注入服务</span></span><br><span class="line"></span><br><span class="line">NgModule(&#123;</span><br><span class="line">  declarations: [</span><br><span class="line">    AppComponent,</span><br><span class="line">    HeaderComponent,</span><br><span class="line">    FooterComponent,</span><br><span class="line">    NewsComponent,</span><br><span class="line">    TodolistComponent</span><br><span class="line">], <span class="attr">imports</span>: [</span><br><span class="line">    BrowserModule,</span><br><span class="line">FormsModule</span><br><span class="line">  ],</span><br><span class="line">  providers: [StorageService],</span><br><span class="line">  bootstrap: [AppComponent]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">AppModule</span> </span>&#123; &#125;</span><br></pre></td></tr></table></figure>
<p><strong>3. 使用的页面引入服务，注册服务</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; StorageService &#125; <span class="keyword">from</span> <span class="string">'../../services/storage.service'</span>;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">constructor</span>(private storage: StorageService) &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 使用</span></span><br><span class="line"></span><br><span class="line">addData()&#123;</span><br><span class="line">     <span class="comment">// alert(this.username);</span></span><br><span class="line">    <span class="keyword">this</span>.list.push(<span class="keyword">this</span>.username); </span><br><span class="line">    <span class="keyword">this</span>.storage.set(<span class="string">'todolist'</span>,<span class="keyword">this</span>.list);</span><br><span class="line">&#125;</span><br><span class="line">removerData(key)&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(key); </span><br><span class="line">    <span class="keyword">this</span>.list.splice(key,<span class="number">1</span>); </span><br><span class="line">    <span class="keyword">this</span>.storage.set(<span class="string">'todolist'</span>,<span class="keyword">this</span>.list);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="4-2-改造上面的Todo、searchList"><a href="#4-2-改造上面的Todo、searchList" class="headerlink" title="4.2 改造上面的Todo、searchList"></a>4.2 改造上面的Todo、searchList</h2><p><strong>searchList</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Component, OnInit &#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 引入服务</span></span><br><span class="line"><span class="keyword">import</span> &#123; StorageService &#125; <span class="keyword">from</span> <span class="string">'../../services/storage.service'</span>;</span><br><span class="line"></span><br><span class="line">@Component(&#123;</span><br><span class="line">  selector: <span class="string">'app-search'</span>,</span><br><span class="line">  templateUrl: <span class="string">'./search.component.html'</span>,</span><br><span class="line">  styleUrls: [<span class="string">'./search.component.scss'</span>]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">SearchComponent</span> <span class="title">implements</span> <span class="title">OnInit</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  public keyword: string;</span><br><span class="line">  public historyList: any[] = [];</span><br><span class="line"></span><br><span class="line">  <span class="keyword">constructor</span>(public storage: StorageService) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span>.storage.get());</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">  ngOnInit() &#123;</span><br><span class="line">   <span class="comment">// 修改的地方</span></span><br><span class="line">    <span class="keyword">var</span> searchlist:any=<span class="keyword">this</span>.storage.get(<span class="string">'searchlist'</span>);</span><br><span class="line">    <span class="keyword">if</span>(searchlist)&#123;</span><br><span class="line">      <span class="keyword">this</span>.historyList=searchlist;        </span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  doSearch()&#123;</span><br><span class="line">    <span class="keyword">if</span>(<span class="keyword">this</span>.historyList.indexOf(<span class="keyword">this</span>.keyword)==<span class="number">-1</span>)&#123;</span><br><span class="line">      <span class="keyword">this</span>.historyList.push(<span class="keyword">this</span>.keyword);</span><br><span class="line">      </span><br><span class="line">      <span class="comment">// 修改的地方</span></span><br><span class="line">      <span class="keyword">this</span>.storage.set(<span class="string">'searchlist'</span>,<span class="keyword">this</span>.historyList);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">this</span>.keyword = <span class="string">''</span>;    </span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  deleteHistroy(key)&#123;</span><br><span class="line">      alert(key);</span><br><span class="line">      <span class="keyword">this</span>.historyList.splice(key,<span class="number">1</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>TODOLIST</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">  ngOnInit() &#123;</span><br><span class="line">  <span class="comment">// 修改的地方</span></span><br><span class="line">    <span class="keyword">var</span> todolist:any=<span class="keyword">this</span>.storage.get(<span class="string">'todolist'</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(todolist)&#123;</span><br><span class="line">      <span class="keyword">this</span>.todolist=todolist;        </span><br><span class="line">    &#125;</span><br><span class="line"> &#125;</span><br><span class="line">doAdd(e)&#123;</span><br><span class="line">    <span class="keyword">if</span>(e.keyCode==<span class="number">13</span>)&#123;</span><br><span class="line">        <span class="keyword">if</span>(!<span class="keyword">this</span>.todolistHasKeyword(<span class="keyword">this</span>.todolist,<span class="keyword">this</span>.keyword))&#123;</span><br><span class="line">          <span class="keyword">this</span>.todolist.push(&#123;</span><br><span class="line">            title:<span class="keyword">this</span>.keyword,</span><br><span class="line">            status:<span class="number">0</span>                   <span class="comment">//0表示代办事项  1表示已完成事项</span></span><br><span class="line">          &#125;);</span><br><span class="line">          <span class="keyword">this</span>.keyword=<span class="string">''</span>;</span><br><span class="line"></span><br><span class="line">          <span class="comment">// 修改的地方</span></span><br><span class="line">          <span class="keyword">this</span>.storage.set(<span class="string">'todolist'</span>,<span class="keyword">this</span>.todolist);          <span class="comment">//用到this一定要注意this指向</span></span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">          alert(<span class="string">'数据已经存在'</span>);</span><br><span class="line">          <span class="keyword">this</span>.keyword=<span class="string">''</span>;</span><br><span class="line">        &#125;</span><br><span class="line">     &#125;</span><br><span class="line">  &#125;</span><br><span class="line"> <span class="comment">// 修改的地方</span></span><br><span class="line">checkboxChange()&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'事件触发了'</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.storage.set(<span class="string">'todolist'</span>,<span class="keyword">this</span>.todolist); </span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">h2</span>&gt;</span>todoList<span class="tag">&lt;/<span class="name">h2</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"todolist"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">"form_input"</span> <span class="attr">type</span>=<span class="string">"text"</span> [(<span class="attr">ngModel</span>)]=<span class="string">"keyword"</span> (<span class="attr">keyup</span>)=<span class="string">"doAdd($event)"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">hr</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">h3</span>&gt;</span>待办事项<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">ul</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">li</span> *<span class="attr">ngFor</span>=<span class="string">"let item of todolist;let key=index;"</span> [<span class="attr">hidden</span>]=<span class="string">"item.status==1"</span>&gt;</span></span><br><span class="line">      <span class="comment">&lt;!-- add checkboxChange--&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"checkbox"</span> [(<span class="attr">ngModel</span>)]=<span class="string">"item.status"</span>  (<span class="attr">change</span>)=<span class="string">"checkboxChange()"</span>/&gt;</span>  &#123;&#123;item.title&#125;&#125;   ------ <span class="tag">&lt;<span class="name">button</span> (<span class="attr">click</span>)=<span class="string">"deleteData(key)"</span>&gt;</span>X<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">h3</span>&gt;</span>已完成事项<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">ul</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">li</span> *<span class="attr">ngFor</span>=<span class="string">"let item of todolist;let key=index;"</span> [<span class="attr">hidden</span>]=<span class="string">"item.status==0"</span>&gt;</span></span><br><span class="line">   <span class="comment">&lt;!-- add checkboxChange--&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"checkbox"</span> [(<span class="attr">ngModel</span>)]=<span class="string">"item.status"</span> (<span class="attr">change</span>)=<span class="string">"checkboxChange()"</span> /&gt;</span>  &#123;&#123;item.title&#125;&#125;   ------ <span class="tag">&lt;<span class="name">button</span> (<span class="attr">click</span>)=<span class="string">"deleteData(key)"</span>&gt;</span>X<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h1 id="五、Dom-操作以及-ViewChild、-执行-css3-动画"><a href="#五、Dom-操作以及-ViewChild、-执行-css3-动画" class="headerlink" title="五、Dom 操作以及@ViewChild、 执行 css3 动画"></a>五、Dom 操作以及@ViewChild、 执行 css3 动画</h1><p><strong>1. Angular 中的 dom 操作(原生 js)</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">ngAfterViewInit()&#123;</span><br><span class="line"><span class="keyword">var</span> boxDom:any=<span class="built_in">document</span>.getElementById(<span class="string">'box'</span>); boxDom.style.color=<span class="string">'red'</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>2. Angular 中的 dom 操作(ViewChild)</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Component ,ViewChild,ElementRef&#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">@ViewChild(<span class="string">'myattr'</span>) myattr: ElementRef;</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> #<span class="attr">myattr</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">ngAfterViewInit()&#123;</span><br><span class="line"><span class="keyword">let</span> attrEl = <span class="keyword">this</span>.myattr.nativeElement;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p> <img src="https://poetries1.gitee.io/img-repo/20191001/32.png" alt></p>
<p><strong>3. 父子组件中通过 ViewChild 调用子组件 的方法</strong></p>
<blockquote>
<p>调用子组件给子组件定义一个名称</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">app-footer</span> #<span class="attr">footerChild</span>&gt;</span><span class="tag">&lt;/<span class="name">app-footer</span>&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>引入 <code>ViewChild</code></p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Component, OnInit ,ViewChild&#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br></pre></td></tr></table></figure>
<blockquote>
<p><code>ViewChild</code> 和刚才的子组件关联起来</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">@ViewChild(<span class="string">'footerChild'</span>) footer</span><br></pre></td></tr></table></figure>
<blockquote>
<p>在父组件中调用子组件方法</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"> run()&#123; </span><br><span class="line">    <span class="keyword">this</span>.footer.footerRun();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="六、Angular-父子组件以及组件之间通讯"><a href="#六、Angular-父子组件以及组件之间通讯" class="headerlink" title="六、Angular 父子组件以及组件之间通讯"></a>六、Angular 父子组件以及组件之间通讯</h1><p> <img src="https://poetries1.gitee.io/img-repo/20191001/33.png" alt></p>
<h2 id="6-1-父组件给子组件传值-input"><a href="#6-1-父组件给子组件传值-input" class="headerlink" title="6.1 父组件给子组件传值-@input"></a>6.1 父组件给子组件传值-@input</h2><blockquote>
<p>父组件不仅可以给子组件传递简单的数据，还可把自己的方法以及整个父组件传给子组件</p>
</blockquote>
<p><strong>1. 父组件调用子组件的时候传入数据</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">app-header</span> [<span class="attr">msg</span>]=<span class="string">"msg"</span>&gt;</span><span class="tag">&lt;/<span class="name">app-header</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>2. 子组件引入 Input 模块</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Component, OnInit ,Input &#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br></pre></td></tr></table></figure>
<p><strong>3. 子组件中 @Input 接收父组件传过来的数据</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">HeaderComponent</span> <span class="title">implements</span> <span class="title">OnInit</span> </span>&#123;</span><br><span class="line">  @Input() msg:string</span><br><span class="line">  </span><br><span class="line">  <span class="keyword">constructor</span>() &#123; &#125;</span><br><span class="line">  </span><br><span class="line">  ngOnInit() &#123;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>4. 子组件中使用父组件的数据</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">p</span>&gt;</span></span><br><span class="line">  child works!</span><br><span class="line">  &#123;&#123;msg&#125;&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>5. 把整个父组件传给子组件</strong></p>
<blockquote>
<p>通过<code>this</code>传递整个组件实例</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">app-header</span> [<span class="attr">home</span>]=<span class="string">"this"</span>&gt;</span><span class="tag">&lt;/<span class="name">app-header</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">HeaderComponent</span> <span class="title">implements</span> <span class="title">OnInit</span> </span>&#123;</span><br><span class="line">  @Input() home:any</span><br><span class="line">  </span><br><span class="line">  <span class="keyword">constructor</span>() &#123; &#125;</span><br><span class="line">  </span><br><span class="line">  ngOnInit() &#123;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>执行父组件方法 <code>this.home.xxx()</code></p>
</blockquote>
<h2 id="6-2-子组件通过-Output-触发父组件的方法（了解）"><a href="#6-2-子组件通过-Output-触发父组件的方法（了解）" class="headerlink" title="6.2 子组件通过@Output 触发父组件的方法（了解）"></a>6.2 子组件通过@Output 触发父组件的方法（了解）</h2><p><strong>1. 子组件引入 Output 和 EventEmitter</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Component, OnInit ,Input,Output,EventEmitter&#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br></pre></td></tr></table></figure>
<p><strong>2. 子组件中实例化 EventEmitter</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">@Output() private outer=<span class="keyword">new</span> EventEmitter&lt;string&gt;(); <span class="comment">/*用EventEmitter和output装饰器配合使用 &lt;string&gt;指定类型变量*/</span></span><br></pre></td></tr></table></figure>
<p><strong>3. 子组件通过 EventEmitter 对象 outer 实例广播数据</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">sendParent()&#123;</span><br><span class="line">  <span class="comment">// alert('zhixing');</span></span><br><span class="line">  <span class="keyword">this</span>.outer.emit(<span class="string">'msg from child'</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>4. 父组件调用子组件的时候，定义接收事件 , outer 就是子组件的 EventEmitter 对象 outer</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--$event就是子组件emit传递的数据--&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">app-header</span> (<span class="attr">outer</span>)=<span class="string">"runParent($event)"</span>&gt;</span><span class="tag">&lt;/<span class="name">app-header</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>5. 父组件接收到数据会调用自己的 runParent 方法，这个时候就能拿到子组件的数据</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">//接收子组件传递过来的数据 </span></span><br><span class="line">runParent(msg:string)&#123;</span><br><span class="line">   alert(msg);</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<h2 id="6-3-父组件通过-ViewChild-主动获取子组-件的数据和方法"><a href="#6-3-父组件通过-ViewChild-主动获取子组-件的数据和方法" class="headerlink" title="6.3 父组件通过@ViewChild 主动获取子组 件的数据和方法"></a>6.3 父组件通过@ViewChild 主动获取子组 件的数据和方法</h2><p><strong>1. 调用子组件给子组件定义一个名称</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">app-footer</span> #<span class="attr">footerChild</span>&gt;</span><span class="tag">&lt;/<span class="name">app-footer</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>2. 引入 ViewChild</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Component, OnInit ,ViewChild&#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br></pre></td></tr></table></figure>
<p><strong>3. ViewChild 和刚才的子组件关联起来</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">@ViewChild(<span class="string">'footerChild'</span>) footer;</span><br></pre></td></tr></table></figure>
<p><strong>4. 调用子组件</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">run()&#123; <span class="keyword">this</span>.footer.footerRun();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="6-4-非父子组件通讯"><a href="#6-4-非父子组件通讯" class="headerlink" title="6.4 非父子组件通讯"></a>6.4 非父子组件通讯</h2><ul>
<li>公共的服务 </li>
<li><code>Localstorage</code> (推荐) </li>
<li><code>Cookie</code></li>
</ul>
<h1 id="七、Angular-中的生命周期函数"><a href="#七、Angular-中的生命周期函数" class="headerlink" title="七、Angular 中的生命周期函数"></a>七、Angular 中的生命周期函数</h1><h2 id="7-1-Angular中的生命周期函数"><a href="#7-1-Angular中的生命周期函数" class="headerlink" title="7.1 Angular中的生命周期函数"></a>7.1 Angular中的生命周期函数</h2><blockquote>
<p>官方文档:<a href="https://www.angular.cn/guide/lifecycle-hooks" target="_blank" rel="noopener">https://www.angular.cn/guide/lifecycle-hooks</a></p>
</blockquote>
<ul>
<li>生命周期函数通俗的讲就是组件创建、组件更新、组件销毁的时候会触发的一系列的方法。</li>
<li>当 <code>Angular</code> 使用构造函数新建一个组件或指令后，就会按下面的顺序在特定时刻调用这些 生命周期钩子方法。</li>
<li>每个接口都有唯一的一个钩子方法，它们的名字是由接口名再加上<code>ng</code>前缀构成的，比如<code>OnInit</code>接口的钩子方法叫做<code>ngOnInit</code>.</li>
</ul>
<p><strong>1. 生命周期钩子分类</strong></p>
<blockquote>
<p>基于指令与组件的区别来分类</p>
</blockquote>
<p><strong>指令与组件共有的钩子</strong></p>
<ul>
<li><code>ngOnChanges</code></li>
<li><code>ngOnInit</code></li>
<li><code>ngDoCheck</code></li>
<li><code>ngOnDestroy</code></li>
</ul>
<p><strong>组件特有的钩子</strong></p>
<ul>
<li><code>ngAfterContentInit</code></li>
<li><code>ngAfterContentChecked</code></li>
<li><code>ngAfterViewInit</code></li>
<li><p><code>ngAfterViewChecked</code></p>
<p><img src="https://poetries1.gitee.io/img-repo/20191001/34.png" alt></p>
</li>
</ul>
<p><strong>2. 生命周期钩子的作用及调用顺序</strong></p>
<p>1、<code>ngOnChanges</code> - 当数据绑定输入属性的值发生变化时调用<br>2、<code>ngOnInit</code> - 在第一次 <code>ngOnChanges</code> 后调用<br>3、<code>ngDoCheck</code> - 自定义的方法，用于检测和处理值的改变<br>4、<code>ngAfterContentInit</code> - 在组件内容初始化之后调用<br>5、<code>ngAfterContentChecked</code> - 组件每次检查内容时调用<br>6、<code>ngAfterViewInit</code> - 组件相应的视图初始化之后调用<br>7、<code>ngAfterViewChecked</code> - 组件每次检查视图时调用<br>8、<code>ngOnDestroy</code> - 指令销毁前调用</p>
<p><strong>3. 首次加载生命周期顺序</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">LifecircleComponent</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">constructor</span>() &#123;</span><br><span class="line"></span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'00构造函数执行了---除了使用简单的值对局部变量进行初始化之外，什么都不应该做'</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ngOnChanges() &#123;</span><br><span class="line"></span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'01ngOnChages执行了---当被绑定的输入属性的值发生变化时调用(父子组件传值的时候会触发)'</span>); </span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ngOnInit() &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'02ngOnInit执行了--- 请求数据一般放在这个里面'</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    ngDoCheck() &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'03ngDoCheck执行了---检测，并在发生 Angular 无法或不愿意自己检测的变化时作出反应'</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    ngAfterContentInit() &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'04ngAfterContentInit执行了---当把内容投影进组件之后调用'</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    ngAfterContentChecked() &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'05ngAfterContentChecked执行了---每次完成被投影组件内容的变更检测之后调用'</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    ngAfterViewInit() : <span class="keyword">void</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'06 ngAfterViewInit执行了----初始化完组件视图及其子视图之后调用（dom操作放在这个里面）'</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    ngAfterViewChecked() &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'07ngAfterViewChecked执行了----每次做完组件视图和子视图的变更检测之后调用'</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ngOnDestroy() &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'08ngOnDestroy执行了····'</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//自定义方法</span></span><br><span class="line">    changeMsg() &#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.msg = <span class="string">"数据改变了"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src="https://upload-images.jianshu.io/upload_images/1480597-7e0081f4616fe461.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="生命周期调用顺序"></p>
<blockquote>
<p>带<code>check</code>的可以对数据做响应操作</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">button</span> (<span class="attr">click</span>)=<span class="string">"changeMsg()"</span>&gt;</span>数据改变了<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">'text'</span> [(<span class="attr">ngModel</span>)]=<span class="string">"userInfo"</span> /&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>点击按钮/双向数据绑定此时触发了以下生命周期。只要数据改变</p>
</blockquote>
<p> <img src="https://poetries1.gitee.io/img-repo/20191001/35.png" alt></p>
<blockquote>
<p>可以在<code>check</code>做一些操作</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">ngDoCheck() &#123;</span><br><span class="line">        <span class="comment">//写一些自定义的操作</span></span><br><span class="line"></span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'03ngDoCheck执行了---检测，并在发生 Angular 无法或不愿意自己检测的变化时作出反应'</span>);</span><br><span class="line">        <span class="keyword">if</span>(<span class="keyword">this</span>.userinfo!==<span class="keyword">this</span>.oldUserinfo)&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">`你从<span class="subst">$&#123;<span class="keyword">this</span>.oldUserinfo&#125;</span>改成<span class="subst">$&#123;<span class="keyword">this</span>.userinfo&#125;</span>`</span>);</span><br><span class="line">            <span class="keyword">this</span>.oldUserinfo = <span class="keyword">this</span>.userinfo;</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            </span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"数据没有变化"</span>);          </span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<h2 id="7-2-生命周期钩子详解"><a href="#7-2-生命周期钩子详解" class="headerlink" title="7.2 生命周期钩子详解"></a>7.2 生命周期钩子详解</h2><h3 id="7-2-1-constructor-掌握"><a href="#7-2-1-constructor-掌握" class="headerlink" title="7.2.1 constructor-掌握"></a>7.2.1 constructor-掌握</h3><blockquote>
<p><code>constructor</code>，来初始化类。<code>Angular</code>中的组件就是基于<code>class</code>类实现的，在<code>Angular</code>中，<code>constructor</code>用于注入依赖。组件的构造函数会在所有的生命周期钩子之前被调用，它主要用于依赖注入或执行简单的数据初始化操作。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Component, ElementRef &#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br><span class="line"></span><br><span class="line">@Component(&#123;</span><br><span class="line">  selector: <span class="string">'my-app'</span>,</span><br><span class="line">  template: <span class="string">`</span></span><br><span class="line"><span class="string">    &lt;h1&gt;Welcome to Angular World&lt;/h1&gt;</span></span><br><span class="line"><span class="string">    &lt;p&gt;Hello &#123;&#123;name&#125;&#125;&lt;/p&gt;</span></span><br><span class="line"><span class="string">  `</span>,</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">AppComponent</span> </span>&#123;</span><br><span class="line">  name: string = <span class="string">''</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">constructor</span>(public elementRef: ElementRef) &#123;<span class="comment">//使用构造注入的方式注入依赖对象</span></span><br><span class="line">    <span class="comment">// 执行初始化操作</span></span><br><span class="line">    <span class="keyword">this</span>.name = <span class="string">'Semlinker'</span>; </span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="7-2-2-ngOnChanges"><a href="#7-2-2-ngOnChanges" class="headerlink" title="7.2.2  ngOnChanges()"></a>7.2.2  ngOnChanges()</h3><blockquote>
<p>当 <code>Angular</code>(重新)设置数据绑定输入属性时响应。该 方法接受当前和上一属性值的 <code>SimpleChanges</code> 对象 当被绑定的输入属性的值发生变化时调用，首次调用一 定会发生在 <code>ngOnInit()</code>之前。</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 父组件中 传递title属性给header子组件 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">app-header</span> [<span class="attr">title</span>]=<span class="string">"title"</span>&gt;</span><span class="tag">&lt;/<span class="name">app-header</span>&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>此时改变<code>title</code>会触发<code>ngOnChanges</code>生命周期，并且也会触发</p>
</blockquote>
<p> <img src="https://poetries1.gitee.io/img-repo/20191001/36.png" alt></p>
<h3 id="7-2-3-ngOnInit-–掌握"><a href="#7-2-3-ngOnInit-–掌握" class="headerlink" title="7.2.3 ngOnInit()–掌握"></a>7.2.3 ngOnInit()–掌握</h3><blockquote>
<p>在 <code>Angular</code> 第一次显示数据绑定和设置指令/组件的输入属性之后，初始化指令/组件。在第一轮 <code>ngOnChanges()</code> 完成之后调用，只调用一次。可以请求数据</p>
</blockquote>
<ul>
<li><strong>使用 ngOnInit() 有两个原因</strong>: <ul>
<li>在构造函数之后马上执行复杂的初始化逻辑</li>
<li>在 <code>Angular</code> 设置完输入属性之后，对该组件进行准备。有经验的开发者会认同组件的构建应该很便宜和安全</li>
</ul>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Component, Input, OnInit &#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br><span class="line"></span><br><span class="line">@Component(&#123;</span><br><span class="line">    selector: <span class="string">'exe-child'</span>,</span><br><span class="line">    template: <span class="string">`</span></span><br><span class="line"><span class="string">     &lt;p&gt;父组件的名称：&#123;&#123;pname&#125;&#125; &lt;/p&gt;</span></span><br><span class="line"><span class="string">    `</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">ChildComponent</span> <span class="title">implements</span> <span class="title">OnInit</span> </span>&#123;</span><br><span class="line">    @Input()</span><br><span class="line">    pname: string; <span class="comment">// 父组件的名称</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">constructor</span>() &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'ChildComponent constructor'</span>, <span class="keyword">this</span>.pname); </span><br><span class="line">        <span class="comment">// Output：undefined</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ngOnInit() &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'ChildComponent ngOnInit'</span>, <span class="keyword">this</span>.pname); </span><br><span class="line">        <span class="comment">// output: 输入的pname值</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="7-2-4-ngDoCheck"><a href="#7-2-4-ngDoCheck" class="headerlink" title="7.2.4 ngDoCheck()"></a>7.2.4 ngDoCheck()</h3><blockquote>
<p>检测，并在发生 <code>Angular</code> 无法或不愿意自己检测的变 化时作出反应。在每个 <code>Angular</code> 变更检测周期中调用， <code>ngOnChanges()</code> 和 <code>ngOnInit()</code>之后。</p>
</blockquote>
<h3 id="7-2-5-ngAfterContentInit"><a href="#7-2-5-ngAfterContentInit" class="headerlink" title="7.2.5 ngAfterContentInit()"></a>7.2.5 ngAfterContentInit()</h3><blockquote>
<p>当把内容投影进组件之后调用。第一次 <code>ngDoCheck()</code> 之后调用，只调用一次</p>
</blockquote>
<h3 id="7-2-6-ngAfterContentChecked"><a href="#7-2-6-ngAfterContentChecked" class="headerlink" title="7.2.6 ngAfterContentChecked()"></a>7.2.6 ngAfterContentChecked()</h3><blockquote>
<p>每次完成被投影组件内容的变更检测之后调用。 <code>ngAfterContentInit()</code> 和每次 <code>ngDoCheck()</code> 之后调</p>
</blockquote>
<h3 id="7-2-7-ngAfterViewInit-–掌握"><a href="#7-2-7-ngAfterViewInit-–掌握" class="headerlink" title="7.2.7 ngAfterViewInit()–掌握"></a>7.2.7 ngAfterViewInit()–掌握</h3><blockquote>
<p>初始化完组件视图及其子视图之后调用。第一 次 <code>ngAfterContentChecked()</code> 之后调用，只调用一次。在这里可以操作<code>DOM</code></p>
</blockquote>
<h3 id="7-2-8-ngAfterViewChecked"><a href="#7-2-8-ngAfterViewChecked" class="headerlink" title="7.2.8 ngAfterViewChecked()"></a>7.2.8 ngAfterViewChecked()</h3><blockquote>
<p>每次做完组件视图和子视图的变更检测之后调用。 <code>ngAfterViewInit()</code>和每次 <code>ngAfterContentChecked()</code> 之后 调用。</p>
</blockquote>
<h3 id="7-2-9-ngOnDestroy-–掌握"><a href="#7-2-9-ngOnDestroy-–掌握" class="headerlink" title="7.2.9 ngOnDestroy()–掌握"></a>7.2.9 ngOnDestroy()–掌握</h3><blockquote>
<p>当 <code>Angular</code> 每次销毁指令/组件之前调用并清扫。在这儿反订阅可观察对象和分离事件处理器，以防内存泄 漏。在 <code>Angular</code> 销毁指令/组件之前调用。比如：移除事件监听、清除定时器、退订 <code>Observable</code> 等。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">@Directive(&#123;</span><br><span class="line">    selector: <span class="string">'[destroyDirective]'</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">OnDestroyDirective</span> <span class="title">implements</span> <span class="title">OnDestroy</span> </span>&#123;</span><br><span class="line">  sayHello: number;</span><br><span class="line">  </span><br><span class="line">  <span class="keyword">constructor</span>() &#123;</span><br><span class="line">    <span class="keyword">this</span>.sayHiya = <span class="built_in">window</span>.setInterval(<span class="function"><span class="params">()</span> =&gt;</span> <span class="built_in">console</span>.log(<span class="string">'hello'</span>), <span class="number">1000</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  ngOnDestroy() &#123;</span><br><span class="line">     <span class="built_in">window</span>.clearInterval(<span class="keyword">this</span>.sayHiya);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="八、Rxjs-异步数据流编程"><a href="#八、Rxjs-异步数据流编程" class="headerlink" title="八、Rxjs 异步数据流编程"></a>八、Rxjs 异步数据流编程</h1><h2 id="8-1-Rxjs介绍"><a href="#8-1-Rxjs介绍" class="headerlink" title="8.1 Rxjs介绍"></a>8.1 Rxjs介绍</h2><blockquote>
<ul>
<li>参考手册:<a href="https://www.npmjs.com/package/rxjs" target="_blank" rel="noopener">https://www.npmjs.com/package/rxjs</a></li>
<li>中文手册:<a href="https://cn.rx.js.org/" target="_blank" rel="noopener">https://cn.rx.js.org/</a></li>
</ul>
</blockquote>
<blockquote>
<p><code>RxJS</code> 是 <code>ReactiveX</code> 编程理念的 <code>JavaScript</code> 版本。<code>ReactiveX</code> 来自微软，它是一种针对异步数据 流的编程。简单来说，它将一切数据，包括 <code>HTTP</code> 请求，<code>DOM</code> 事件或者普通数据等包装成流的形式，然后用强大丰富的操作符对流进行处理，使你能以同步编程的方式处理异步数据，并组合不同的操作符来轻松优雅的实现你所需要的功能。</p>
</blockquote>
<ul>
<li><code>RxJS</code> 是一种针对异步数据流编程工具，或者叫响应式扩展编程;可不管如何解释 RxJS 其目 标就是异步编程，<code>Angular</code> 引入 <code>RxJS</code> 为了就是让异步可控、更简单。</li>
<li><code>RxJS</code> 里面提供了很多模块。这里我们主要给大家讲 <code>RxJS</code> 里面最常用的<code>Observable</code> 和 f<code>romEvent</code></li>
</ul>
<p><strong>目前常见的异步编程的几种方法:</strong></p>
<ul>
<li>回调函数 </li>
<li>事件监听/发布订阅 </li>
<li><code>Promise</code></li>
<li><code>Rxjs</code></li>
</ul>
<h2 id="8-2-Promise和RxJS处理异步对比"><a href="#8-2-Promise和RxJS处理异步对比" class="headerlink" title="8.2 Promise和RxJS处理异步对比"></a>8.2 Promise和RxJS处理异步对比</h2><blockquote>
<p>新建一个<code>services</code></p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">ng g service services/rxjs</span><br></pre></td></tr></table></figure>
<blockquote>
<p>在<code>services/rxjs.service.ts</code>中写以下方法</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Injectable &#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; Observable &#125; <span class="keyword">from</span> <span class="string">'rxjs'</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">@Injectable(&#123;</span><br><span class="line">  providedIn: <span class="string">'root'</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">RxjsService</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>() &#123; &#125;</span><br><span class="line">  </span><br><span class="line"> <span class="comment">// Promise 处理异步</span></span><br><span class="line">  getPromiseData() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(resolve = &gt;&#123;</span><br><span class="line">    setTimeout(() = &gt;&#123;</span><br><span class="line">        resolve(<span class="string">'---promise timeout---'</span>);</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="number">2000</span>);</span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// RxJS 处理异步:</span></span><br><span class="line">getRxjsData() &#123;</span><br><span class="line">   <span class="keyword">return</span> <span class="keyword">new</span> Observable(observer = &gt;&#123;</span><br><span class="line">      setTimeout(() = &gt;&#123;</span><br><span class="line">        observer.next(<span class="string">'observable timeout'</span>);</span><br><span class="line">      &#125;,</span><br><span class="line">      <span class="number">2000</span>);</span><br><span class="line">  &#125;); </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 在其他组件使用服务</span></span><br><span class="line"><span class="keyword">import</span> &#123; Component, OnInit &#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; RxjsService &#125; <span class="keyword">from</span> <span class="string">'../../services/rxjs.service'</span>;</span><br><span class="line"></span><br><span class="line">@Component(&#123;</span><br><span class="line">  selector: <span class="string">'app-rxjs'</span>,</span><br><span class="line">  templateUrl: <span class="string">'./rxjs.component.html'</span>,</span><br><span class="line">  styleUrls: [<span class="string">'./rxjs.component.scss'</span>]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">RxjsComponent</span> <span class="title">implements</span> <span class="title">OnInit</span> </span>&#123;</span><br><span class="line">  </span><br><span class="line">  <span class="comment">// 注入服务</span></span><br><span class="line">  <span class="keyword">constructor</span>(public request: RxjsService) &#123;</span><br><span class="line"></span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">  ngOnInit() &#123;</span><br><span class="line">    <span class="comment">// 调用方法</span></span><br><span class="line">     <span class="keyword">this</span>.request.getRxjsData().subscribe(<span class="function"><span class="params">data</span>=&gt;</span>&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(data)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>从上面列子可以看到 <code>RxJS</code> 和 <code>Promise</code>的基本用法非常类似，除了一些关键词不同。<code>Promise</code> 里面用的是 <code>then()</code> 和 <code>resolve()</code>，而 <code>RxJS</code>里面用的是 <code>next()</code> 和 <code>subscribe()</code></li>
<li><code>Rxjs</code>相比<code>Promise</code>要强大很多。 比如 <code>Rxjs</code> 中可以中途撤回、<code>Rxjs</code> 可以发射多个值、<code>Rxjs</code> 提供了多种工具函数等等</li>
</ul>
<h2 id="8-3-Rxjs-unsubscribe-取消订阅"><a href="#8-3-Rxjs-unsubscribe-取消订阅" class="headerlink" title="8.3 Rxjs unsubscribe 取消订阅"></a>8.3 Rxjs unsubscribe 取消订阅</h2><blockquote>
<p><code>Promise</code> 的创建之后，动作是无法撤回的。<code>Observable</code> 不一样，动作可以通过 <code>unsbscribe()</code> 方法中途撤回，而且 <code>Observable</code> 在内部做了智能的处理.</p>
</blockquote>
<p><strong>Promise 创建之后动作无法撤回</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> promise = <span class="keyword">new</span> <span class="built_in">Promise</span>(resolve = &gt;&#123;</span><br><span class="line">    setTimeout(() = &gt;&#123;</span><br><span class="line">        resolve(<span class="string">'---promise timeout---'</span>);</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="number">2000</span>);</span><br><span class="line">&#125;);</span><br><span class="line">promise.then(value = &gt;<span class="built_in">console</span>.log(value));</span><br></pre></td></tr></table></figure>
<p><strong>Rxjs 可以通过 unsubscribe() 可以撤回 subscribe 的动作</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> stream = <span class="keyword">new</span> Observable(observer = &gt;&#123;</span><br><span class="line">    <span class="keyword">let</span> timeout = setTimeout(() = &gt;&#123;</span><br><span class="line">        clearTimeout(timeout);</span><br><span class="line">        observer.next(<span class="string">'observable timeout'</span>);</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="number">2000</span>);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="keyword">let</span> disposable = stream.subscribe(value = &gt;<span class="built_in">console</span>.log(value));</span><br><span class="line">setTimeout(() = &gt;&#123;</span><br><span class="line">    <span class="comment">//取消执行 disposable.unsubscribe();</span></span><br><span class="line">&#125;,</span><br><span class="line"><span class="number">1000</span>);</span><br></pre></td></tr></table></figure>
<h2 id="8-4-Rxjs-订阅后多次执行"><a href="#8-4-Rxjs-订阅后多次执行" class="headerlink" title="8.4 Rxjs 订阅后多次执行"></a>8.4 Rxjs 订阅后多次执行</h2><ul>
<li>如果我们想让异步里面的方法多次执行，比如下面代码。</li>
</ul>
<blockquote>
<p>这一点 <code>Promise</code>是做不到的，对于 <code>Promise</code>来说，最终结果要么 <code>resole</code>(兑现)、要么 <code>reject</code> (拒绝)，而且都只能触发一次。如果在同一个 <code>Promise</code> 对象上多次调用 <code>resolve</code> 方法， 则会抛异常。而 <code>Observable</code>不一样，它可以不断地触发下一个值，就像 <code>next()</code>这个方法的 名字所暗示的那样。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> promise = <span class="keyword">new</span> <span class="built_in">Promise</span>(resolve = &gt;&#123;</span><br><span class="line">    setInterval(() = &gt;&#123;</span><br><span class="line">        resolve(<span class="string">'---promise setInterval---'</span>);</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="number">2000</span>);</span><br><span class="line">&#125;);</span><br><span class="line">promise.then(value = &gt;<span class="built_in">console</span>.log(value));</span><br></pre></td></tr></table></figure>
<p><strong>Rxjs</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> stream = <span class="keyword">new</span> Observable &lt; number &gt; (observer = &gt;&#123;</span><br><span class="line">    <span class="keyword">let</span> count = <span class="number">0</span>;</span><br><span class="line">    setInterval(() = &gt;&#123;</span><br><span class="line">        observer.next(count++);</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="number">1000</span>);</span><br><span class="line">&#125;);</span><br><span class="line">stream.subscribe(value = &gt;<span class="built_in">console</span>.log(<span class="string">"Observable&gt;"</span> + value));</span><br></pre></td></tr></table></figure>
<h2 id="8-5-Angualr6-x之前使用Rxjs的工具函数-map-filter"><a href="#8-5-Angualr6-x之前使用Rxjs的工具函数-map-filter" class="headerlink" title="8.5 Angualr6.x之前使用Rxjs的工具函数 map filter"></a>8.5 Angualr6.x之前使用Rxjs的工具函数 map filter</h2><blockquote>
<p>注意:<code>Angular6</code> 以后使用以前的<code>rxjs</code> 方法，必须安装 <code>rxjs-compat</code> 模块才可以使用 <code>map</code>、<code>filter</code> 方法。</p>
</blockquote>
<blockquote>
<p><code>angular6</code> 后官方使用的是 <code>RXJS6</code>的新特性，所以官方给出了一个可以暂时延缓我们不需要修 改 <code>rsjx</code> 代码的办法</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">npm install rxjs-compat</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;Observable&#125; <span class="keyword">from</span> <span class="string">'rxjs'</span>; <span class="keyword">import</span> <span class="string">'rxjs/Rx'</span>;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> stream = <span class="keyword">new</span> Observable &lt; any &gt; (observer = &gt;&#123;</span><br><span class="line">    <span class="keyword">let</span> count = <span class="number">0</span>;</span><br><span class="line">    setInterval(() = &gt;&#123;</span><br><span class="line">        observer.next(count++);</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="number">1000</span>);</span><br><span class="line">&#125;);</span><br><span class="line">stream.filter(val = &gt;val % <span class="number">2</span> == <span class="number">0</span>).subscribe(value = &gt;<span class="built_in">console</span>.log(<span class="string">"filter&gt;"</span> + value));</span><br><span class="line">stream.map(value = &gt;&#123;</span><br><span class="line">    <span class="keyword">return</span> value * value</span><br><span class="line">&#125;).subscribe(value = &gt;<span class="built_in">console</span>.log(<span class="string">"map&gt;"</span> + value));</span><br></pre></td></tr></table></figure>
<h2 id="8-6-Angualr6-x-以后-Rxjs6-x-的变化以及-使用"><a href="#8-6-Angualr6-x-以后-Rxjs6-x-的变化以及-使用" class="headerlink" title="8.6 Angualr6.x 以后 Rxjs6.x 的变化以及 使用"></a>8.6 Angualr6.x 以后 Rxjs6.x 的变化以及 使用</h2><h3 id="8-6-1-Rxjs-的变化参考"><a href="#8-6-1-Rxjs-的变化参考" class="headerlink" title="8.6.1 Rxjs 的变化参考"></a>8.6.1 Rxjs 的变化参考</h3><blockquote>
<p>从<code>Angular5</code>升级到<code>Angular6</code>， <code>angular6</code>相比较于<code>angular5</code>总体变化不大，但是在<code>RXJS</code>上面却有一些变动，下面给大家讲讲关于<code>Angular6</code>版本升级和<code>RXJS6</code>新特性的讲解</p>
</blockquote>
<p><strong>1. angular6 Angular7中使用以前的rxjs</strong></p>
<blockquote>
<p>对于写了半年多的项目，模块已经很多了，所以不可能在升级到<code>angular6</code>后马上更新所有代码关于<code>RXJS6</code>的新特性，所以官方给出了一个可以暂时延缓我们不需要修改<code>rsjx</code>代码的办法。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">npm install --save rxjs-compat</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>优点</strong>： 暂时不用改代码，可以一点点地改，直到改完后吧这个包卸掉</li>
<li><strong>缺点</strong>： 对于<code>rxjs6</code>的<code>rename</code>的<code>operator</code>无效，所以，如果有用到<code>rename</code>的<code>API</code>，必须手动修改</li>
</ul>
<p><strong>2. Angular6 以后 RXJS6的变化</strong></p>
<blockquote>
<p><code>RXJS6</code>改变了包的结构，主要变化在 <code>import</code>方式和<code>operator</code>上面以及使用<code>pipe()</code></p>
</blockquote>
<p><strong>2.1 Imports 方式改变</strong></p>
<p> <img src="https://poetries1.gitee.io/img-repo/20191001/37.png" alt></p>
<blockquote>
<p>从<code>rxjs</code>中类似像导入<code>observable</code> <code>subject</code> 等的不再进一步导入，而是止于<code>rxjs</code>, <code>rxjs6</code>在包的结构上进行了改变</p>
</blockquote>
<p><strong>2.2 operator的改变</strong></p>
<p> <img src="https://poetries1.gitee.io/img-repo/20191001/38.png" alt></p>
<blockquote>
<p>总而言之： 类似于创建之类的用的<code>API</code>都是从<code>rxjs</code>引入的，类似于<code>map</code> 之类的操作都是从<code>rxjs/operators</code>引入的</p>
</blockquote>
<p> <img src="https://poetries1.gitee.io/img-repo/20191001/39.png" alt></p>
<p><strong>2.3 pipeable observable</strong></p>
<p> <img src="https://poetries1.gitee.io/img-repo/20191001/40.png" alt></p>
<p><strong>2.4 被重新命名的API</strong></p>
<p> <img src="https://poetries1.gitee.io/img-repo/20191001/41.png" alt></p>
<blockquote>
<p><code>RXJS6</code> 改变了包的结构，主要变化在 <code>import</code> 方式和 <code>operator</code> 上面以及使用 <code>pipe()</code></p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;Observable&#125; <span class="keyword">from</span> <span class="string">'rxjs'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123;map,filter&#125; <span class="keyword">from</span> <span class="string">'rxjs/operators'</span>;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> stream= <span class="keyword">new</span> Observable&lt;any&gt;(<span class="function"><span class="params">observer</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">let</span> count = <span class="number">0</span>;</span><br><span class="line">    setInterval(() = &gt;&#123;</span><br><span class="line">        observer.next(count++);</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="number">1000</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">stream.pipe(filter(val = &gt;val % <span class="number">2</span> == <span class="number">0</span>))</span><br><span class="line">.subscribe(value = &gt;<span class="built_in">console</span>.log(<span class="string">"filter&gt;"</span> + value));</span><br><span class="line"></span><br><span class="line">stream</span><br><span class="line">.pipe(</span><br><span class="line">    filter(val = &gt;val % <span class="number">2</span> == <span class="number">0</span>), </span><br><span class="line">    map(value = &gt;&#123;</span><br><span class="line">        <span class="keyword">return</span> value * value</span><br><span class="line">&#125;))</span><br><span class="line">.subscribe(value = &gt;<span class="built_in">console</span>.log(<span class="string">"map&gt;"</span> + value));</span><br></pre></td></tr></table></figure>
<h2 id="8-7-Rxjs-延迟执行"><a href="#8-7-Rxjs-延迟执行" class="headerlink" title="8.7 Rxjs 延迟执行"></a>8.7 Rxjs 延迟执行</h2><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;</span><br><span class="line">    Observable,</span><br><span class="line">    fromEvent</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">from</span> <span class="string">'rxjs'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123;</span><br><span class="line">    map,</span><br><span class="line">    filter,</span><br><span class="line">    throttleTime</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">from</span> <span class="string">'rxjs/operators'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> button = <span class="built_in">document</span>.querySelector(<span class="string">'button'</span>);</span><br><span class="line"></span><br><span class="line">fromEvent(button, <span class="string">'click'</span>)</span><br><span class="line">.pipe(throttleTime(<span class="number">1000</span>))</span><br><span class="line">.subscribe(() = &gt;<span class="built_in">console</span>.log(<span class="string">`Clicked`</span>));</span><br></pre></td></tr></table></figure>
<h1 id="九、Angular-中的数据交互-get-jsonp-post"><a href="#九、Angular-中的数据交互-get-jsonp-post" class="headerlink" title="九、Angular 中的数据交互(get jsonp post)"></a>九、Angular 中的数据交互(get jsonp post)</h1><h2 id="9-1-Angular-get-请求数据"><a href="#9-1-Angular-get-请求数据" class="headerlink" title="9.1 Angular get 请求数据"></a>9.1 Angular get 请求数据</h2><blockquote>
<p><code>Angular5.x</code> 以后 <code>get</code>、<code>post</code> 和和服务器交互使用的是 <code>HttpClientModule</code> 模块。</p>
</blockquote>
<p><strong>1. 在 app.module.ts 中引入 HttpClientModule 并注入</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;HttpClientModule&#125; <span class="keyword">from</span> <span class="string">'@angular/common/http'</span>;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">imports: [</span><br><span class="line">    BrowserModule,</span><br><span class="line">    HttpClientModule</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<p><strong>2. 在用到的地方引入 HttpClient 并在构造函数声明</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;HttpClient&#125; <span class="keyword">from</span> <span class="string">"@angular/common/http"</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">constructor</span>(public http:HttpClient) &#123; &#125;</span><br></pre></td></tr></table></figure>
<p><strong>3. get 请求数据</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> api = <span class="string">"http://a.itying.com/api/productlist"</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">this</span>.http.get(api).subscribe(<span class="function"><span class="params">response</span> =&gt;</span> &#123;</span><br><span class="line"><span class="built_in">console</span>.log(response); &#125;);</span><br></pre></td></tr></table></figure>
<h2 id="9-2-Angular-post-提交数据"><a href="#9-2-Angular-post-提交数据" class="headerlink" title="9.2 Angular post 提交数据"></a>9.2 Angular post 提交数据</h2><blockquote>
<p><code>Angular5.x</code> 以后 <code>get</code>、<code>post</code> 和和服务器交互使用的是<code>HttpClientModule</code> 模块。</p>
</blockquote>
<p><strong>1. 在 app.module.ts 中引入 HttpClientModule 并注入</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;HttpClientModule&#125; <span class="keyword">from</span> <span class="string">'@angular/common/http'</span>;</span><br><span class="line"></span><br><span class="line">imports: [</span><br><span class="line">    BrowserModule,</span><br><span class="line">    HttpClientModule</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<p><strong>2. 在用到的地方引入 HttpClient、HttpHeaders 并在构造函数声明 HttpClient</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;HttpClient,HttpHeaders&#125; <span class="keyword">from</span> <span class="string">"@angular/common/http"</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">constructor</span>(public http:HttpClient) &#123; &#125;</span><br></pre></td></tr></table></figure>
<p><strong>3. post 提交数据</strong></p>
<blockquote>
<p>用<code>express</code>搭建一个<code>server</code></p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// package.json</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="string">"dependencies"</span>: &#123;</span><br><span class="line">    <span class="string">"ejs"</span>: <span class="string">"^2.5.6"</span>,</span><br><span class="line">    <span class="string">"express"</span>: <span class="string">"^4.15.3"</span>,</span><br><span class="line">    <span class="string">"socket.io"</span>: <span class="string">"^2.0.3"</span>,</span><br><span class="line">    <span class="string">"body-parser"</span>: <span class="string">"~1.17.1"</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// app.js 代码</span></span><br><span class="line"><span class="keyword">var</span> express = <span class="built_in">require</span>(<span class="string">'express'</span>);</span><br><span class="line"><span class="keyword">var</span> app=express();</span><br><span class="line"><span class="keyword">var</span> bodyParser = <span class="built_in">require</span>(<span class="string">'body-parser'</span>);</span><br><span class="line"></span><br><span class="line">app.use(bodyParser.json());</span><br><span class="line">app.use(bodyParser.urlencoded(&#123; <span class="attr">extended</span>: <span class="literal">false</span> &#125;));</span><br><span class="line"></span><br><span class="line"><span class="comment">/*express允许跨域*/</span></span><br><span class="line">app.all(<span class="string">'*'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res, next</span>) </span>&#123;</span><br><span class="line">    res.header(<span class="string">"Access-Control-Allow-Origin"</span>, <span class="string">"*"</span>);</span><br><span class="line">    res.header(<span class="string">"Access-Control-Allow-Headers"</span>, <span class="string">"Content-Type,Content-Length, Authorization, Accept,X-Requested-With"</span>);</span><br><span class="line">    res.header(<span class="string">"Access-Control-Allow-Methods"</span>,<span class="string">"PUT,POST,GET,DELETE,OPTIONS"</span>);</span><br><span class="line">    res.header(<span class="string">"X-Powered-By"</span>,<span class="string">' 3.2.1'</span>)</span><br><span class="line">    <span class="keyword">if</span>(req.method==<span class="string">"OPTIONS"</span>) res.send(<span class="number">200</span>);</span><br><span class="line">    <span class="keyword">else</span>  next();</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//app.use(express.static(path.join(__dirname, 'public')));</span></span><br><span class="line"></span><br><span class="line">app.get(<span class="string">'/'</span>,<span class="function"><span class="keyword">function</span>(<span class="params">req,res</span>)</span>&#123;</span><br><span class="line">	res.send(<span class="string">'首页'</span>);</span><br><span class="line">&#125;)</span><br><span class="line">app.post(<span class="string">'/dologin'</span>,<span class="function"><span class="keyword">function</span>(<span class="params">req,res</span>)</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(req.body);</span><br><span class="line"> 	res.json(&#123;<span class="string">"msg"</span>:<span class="string">'post成功'</span>&#125;);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">'/news'</span>,<span class="function"><span class="keyword">function</span>(<span class="params">req,res</span>)</span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//console.log(req.body);</span></span><br><span class="line">	res.jsonp(&#123;<span class="string">"msg"</span>:<span class="string">'这是新闻数据'</span>&#125;);</span><br><span class="line"></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">app.listen(<span class="number">3000</span>,<span class="string">'127.0.0.1'</span>,<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">   <span class="built_in">console</span>.log(<span class="string">'项目启动在3000端口'</span>)</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// angular代码</span></span><br><span class="line"></span><br><span class="line">doLogin() &#123;</span><br><span class="line">  </span><br><span class="line">  <span class="comment">// 手动设置请求类型</span></span><br><span class="line">  <span class="keyword">const</span> httpOptions = &#123;</span><br><span class="line">    headers: <span class="keyword">new</span> HttpHeaders(&#123;</span><br><span class="line">        <span class="string">'Content-Type'</span>: <span class="string">'application/json'</span></span><br><span class="line">    &#125;)</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">var</span> api = <span class="string">"http://127.0.0.1:3000/doLogin"</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">this</span>.http.post(api, &#123;</span><br><span class="line">    username: <span class="string">'张三'</span>,</span><br><span class="line">    age: <span class="string">'20'</span></span><br><span class="line">&#125;,</span><br><span class="line">httpOptions).subscribe(response = &gt;&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(response);</span><br><span class="line">&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="9-3-Angular-Jsonp-请求数据"><a href="#9-3-Angular-Jsonp-请求数据" class="headerlink" title="9.3 Angular Jsonp 请求数据"></a>9.3 Angular Jsonp 请求数据</h2><p><strong>1. 在 app.module.ts 中引入 HttpClientModule、HttpClientJsonpModule 并注入</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;HttpClientModule,HttpClientJsonpModule&#125; <span class="keyword">from</span> <span class="string">'@angular/common/http'</span>;</span><br></pre></td></tr></table></figure>
 <figure class="highlight js"><table><tr><td class="code"><pre><span class="line"> imports: [</span><br><span class="line">  BrowserModule,</span><br><span class="line">  HttpClientModule,</span><br><span class="line">  HttpClientJsonpModule</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<p><strong>3. 在用到的地方引入 HttpClient 并在构造函数声明</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;HttpClient&#125; <span class="keyword">from</span> <span class="string">"@angular/common/http"</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">constructor</span>(public http:HttpClient) &#123; &#125;</span><br></pre></td></tr></table></figure>
<p><strong>3. jsonp 请求数据</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 接口支持jsonp请求</span></span><br><span class="line"><span class="keyword">var</span> api = <span class="string">"http://a.itying.com/api/productlist"</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">this</span>.http.jsonp(api,<span class="string">'callback'</span>).subscribe(<span class="function"><span class="params">response</span> =&gt;</span> &#123;</span><br><span class="line"><span class="built_in">console</span>.log(response); &#125;);</span><br></pre></td></tr></table></figure>
<h2 id="9-4-Angular-中使用第三方模块-axios-请求数据"><a href="#9-4-Angular-中使用第三方模块-axios-请求数据" class="headerlink" title="9.4 Angular 中使用第三方模块 axios 请求数据"></a>9.4 Angular 中使用第三方模块 axios 请求数据</h2><p><strong>1. 安装 axios</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">cnpm install axios --save</span><br></pre></td></tr></table></figure>
<p><strong>2. 用到的地方引入 axios</strong></p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">import axios from &apos;axios&apos;;</span><br></pre></td></tr></table></figure>
<p><strong>3. 看文档使用</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">axios.get(<span class="string">'/user?ID=12345'</span>).then(<span class="function"><span class="keyword">function</span>(<span class="params">response</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// handle success</span></span><br><span class="line">    <span class="built_in">console</span>.log(response);</span><br><span class="line">&#125;).</span><br><span class="line"><span class="keyword">catch</span>(<span class="function"><span class="keyword">function</span>(<span class="params">error</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// handle error console.log(error);</span></span><br><span class="line">&#125;).then(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// always executed </span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h1 id="十、Angular-中的路由"><a href="#十、Angular-中的路由" class="headerlink" title="十、Angular 中的路由"></a>十、Angular 中的路由</h1><h2 id="10-1-Angular-创建一个默认带路由的项目"><a href="#10-1-Angular-创建一个默认带路由的项目" class="headerlink" title="10.1 Angular 创建一个默认带路由的项目"></a>10.1 Angular 创建一个默认带路由的项目</h2><p><strong>1. 命令创建项目</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">ng <span class="keyword">new</span> angualrdemo08 --skip-install</span><br></pre></td></tr></table></figure>
<p><strong>2. 创建需要的组件</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">ng g component home</span><br><span class="line">ng g component news</span><br><span class="line">ng g component newscontent</span><br></pre></td></tr></table></figure>
<p><strong>3. 找到 app-routing.module.ts 配置路由</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 引入组件</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> &#123; HomeComponent &#125; <span class="keyword">from</span> <span class="string">'./home/home.component'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; NewsComponent &#125; <span class="keyword">from</span> <span class="string">'./news/news.component'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; NewscontentComponent &#125; <span class="keyword">from</span> <span class="string">'./newscontent/newscontent.component'</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 配置路由</span></span><br><span class="line"><span class="keyword">const</span> routes: Routes = [</span><br><span class="line">  &#123;<span class="attr">path</span>: <span class="string">'home'</span>, <span class="attr">component</span>: HomeComponent&#125;,</span><br><span class="line">  &#123;<span class="attr">path</span>: <span class="string">'news'</span>, <span class="attr">component</span>: NewsComponent&#125;,</span><br><span class="line">  &#123;<span class="attr">path</span>: <span class="string">'newscontent/:id'</span>, <span class="attr">component</span>: NewscontentComponent&#125;,</span><br><span class="line">  &#123;</span><br><span class="line">    path: <span class="string">''</span>,</span><br><span class="line">    redirectTo: <span class="string">'/home'</span>,</span><br><span class="line">    pathMatch: <span class="string">'full'</span></span><br><span class="line">&#125; ];</span><br></pre></td></tr></table></figure>
<p><strong>4. 找到 app.component.html 根组件模板，配置 router-outlet 显示动态加载的路由</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">h1</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">a</span> <span class="attr">routerLink</span>=<span class="string">"/home"</span>&gt;</span>首页<span class="tag">&lt;/<span class="name">a</span>&gt;</span> <span class="tag">&lt;<span class="name">a</span> <span class="attr">routerLink</span>=<span class="string">"/news"</span>&gt;</span>新闻<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">router-outlet</span>&gt;</span><span class="tag">&lt;/<span class="name">router-outlet</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="10-2-routerLink-跳转页面-默认路由"><a href="#10-2-routerLink-跳转页面-默认路由" class="headerlink" title="10.2 routerLink 跳转页面 默认路由"></a>10.2 routerLink 跳转页面 默认路由</h2><figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">a</span> <span class="attr">routerLink</span>=<span class="string">"/home"</span>&gt;</span>首页<span class="tag">&lt;/<span class="name">a</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="name">a</span> <span class="attr">routerLink</span>=<span class="string">"/news"</span>&gt;</span>新闻<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br></pre></td></tr></table></figure>
 <figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">//匹配不到路由的时候加载的组件 或者跳转的路由</span></span><br><span class="line">&#123;</span><br><span class="line">    path: <span class="string">'**'</span>, <span class="comment">/*任意的路由*/</span> </span><br><span class="line">    <span class="comment">// component:HomeComponent </span></span><br><span class="line">    redirectTo:<span class="string">'home'</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="10-3-routerLinkActive-设置routerLink-默认选中路由"><a href="#10-3-routerLinkActive-设置routerLink-默认选中路由" class="headerlink" title="10.3 routerLinkActive 设置routerLink 默认选中路由"></a>10.3 routerLinkActive 设置routerLink 默认选中路由</h2><figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">h1</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">a</span> <span class="attr">routerLink</span>=<span class="string">"/home"</span> <span class="attr">routerLinkActive</span>=<span class="string">"active"</span>&gt;</span>首页<span class="tag">&lt;/<span class="name">a</span>&gt;</span> <span class="tag">&lt;<span class="name">a</span> <span class="attr">routerLink</span>=<span class="string">"/news"</span> <span class="attr">routerLinkActive</span>=<span class="string">"active"</span>&gt;</span>新闻<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">h1</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">a</span> [<span class="attr">routerLink</span>]=<span class="string">"[ '/home' ]"</span> <span class="attr">routerLinkActive</span>=<span class="string">"active"</span>&gt;</span>首页<span class="tag">&lt;/<span class="name">a</span>&gt;</span> <span class="tag">&lt;<span class="name">a</span> [<span class="attr">routerLink</span>]=<span class="string">"[ '/news' ]"</span> <span class="attr">routerLinkActive</span>=<span class="string">"active"</span>&gt;</span>新闻<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight css"><table><tr><td class="code"><pre><span class="line"> <span class="selector-class">.active</span>&#123;</span><br><span class="line">    <span class="attribute">color</span>:red;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="10-4-routerLink-Get传递参数"><a href="#10-4-routerLink-Get传递参数" class="headerlink" title="10.4 routerLink Get传递参数"></a>10.4 routerLink Get传递参数</h2><p><strong>1. 跳转</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">li</span> *<span class="attr">ngFor</span>=<span class="string">"let item of list;let key=index;"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- &lt;a href="/news-detail?aid=123"&gt;&#123;&#123;key&#125;&#125;--&#123;&#123;item&#125;&#125;&lt;/a&gt; --&gt;</span></span><br><span class="line">     </span><br><span class="line">    <span class="tag">&lt;<span class="name">a</span> [<span class="attr">routerLink</span>]=<span class="string">"['/news-detail']"</span> [<span class="attr">queryParams</span>]=<span class="string">"&#123;aid:key&#125;"</span>&gt;</span>&#123;&#123;key&#125;&#125;--&#123;&#123;item&#125;&#125;<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line"></span><br><span class="line">  <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>2. 接收参数</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"> <span class="keyword">import</span> &#123; ActivatedRoute &#125; <span class="keyword">from</span> <span class="string">'@angular/router'</span>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">constructor</span>(public route:ActivatedRoute) &#123; &#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">this</span>.route.queryParams.subscribe(<span class="function">(<span class="params">data</span>)=&gt;</span>&#123;</span><br><span class="line">     <span class="built_in">console</span>.log(data);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h2 id="10-5-动态路由"><a href="#10-5-动态路由" class="headerlink" title="10.5 动态路由"></a>10.5 动态路由</h2><p><strong>1.配置动态路由</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> routes: Routes = [</span><br><span class="line">  &#123;<span class="attr">path</span>: <span class="string">'home'</span>, <span class="attr">component</span>: HomeComponent&#125;,</span><br><span class="line">  &#123;<span class="attr">path</span>: <span class="string">'news'</span>, <span class="attr">component</span>: NewsComponent&#125;,</span><br><span class="line">  &#123;<span class="attr">path</span>: <span class="string">'newscontent/:id'</span>, <span class="attr">component</span>: NewscontentComponent&#125;,</span><br><span class="line">  &#123;</span><br><span class="line">    path: <span class="string">''</span>,</span><br><span class="line">    redirectTo: <span class="string">'/home'</span>,</span><br><span class="line">    pathMatch: <span class="string">'full'</span></span><br><span class="line">&#125; ];</span><br></pre></td></tr></table></figure>
<p><strong>2. 跳转传值</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">a</span> [<span class="attr">routerLink</span>]=<span class="string">"[ '/newscontent/',aid]"</span>&gt;</span>跳转到详情<span class="tag">&lt;/<span class="name">a</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="name">a</span> <span class="attr">routerLink</span>=<span class="string">"/newscontent/&#123;&#123;aid&#125;&#125;"</span>&gt;</span>跳转到详情<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>3. 获取动态路由的值</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; ActivatedRoute&#125; <span class="keyword">from</span> <span class="string">'@angular/router'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">constructor</span>( private route: ActivatedRoute) &#123; &#125;</span><br><span class="line"> </span><br><span class="line">ngOnInit() &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="keyword">this</span>.route.params);</span><br><span class="line">  <span class="keyword">this</span>.route.params.subscribe(<span class="function"><span class="params">data</span>=&gt;</span><span class="keyword">this</span>.id=data.id);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="10-6-动态路由的-js-跳转"><a href="#10-6-动态路由的-js-跳转" class="headerlink" title="10.6 动态路由的 js 跳转"></a>10.6 动态路由的 js 跳转</h2><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 引入</span></span><br><span class="line"><span class="keyword">import</span> &#123; Router &#125; <span class="keyword">from</span> <span class="string">'@angular/router'</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 初始化</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">HomeComponent</span> <span class="title">implements</span> <span class="title">OnInit</span> </span>&#123; </span><br><span class="line">    <span class="keyword">constructor</span>(private router: Router) &#123;&#125;</span><br><span class="line">    ngOnInit() &#123;&#125;</span><br><span class="line">    goNews()&#123;</span><br><span class="line">    <span class="comment">// this.router.navigate(['/news', hero.id]);</span></span><br><span class="line">         <span class="keyword">this</span>.router.navigate([<span class="string">'/news'</span>]);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 路由跳转</span></span><br><span class="line"><span class="keyword">this</span>.router.navigate([<span class="string">'/news'</span>, hero.id]);</span><br></pre></td></tr></table></figure>
<h2 id="10-7-路由-get-传值-js-跳转"><a href="#10-7-路由-get-传值-js-跳转" class="headerlink" title="10.7 路由 get 传值 js 跳转"></a>10.7 路由 get 传值 js 跳转</h2><p><strong>1. 引入 NavigationExtras</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Router ,NavigationExtras&#125; <span class="keyword">from</span> <span class="string">'@angular/router'</span>;</span><br></pre></td></tr></table></figure>
<p><strong>2. 定义一个 goNewsContent 方法执行跳转，用 NavigationExtras 配置传参。</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">goNewsContent() &#123;</span><br><span class="line">    <span class="keyword">let</span> navigationExtras: NavigationExtras = &#123;</span><br><span class="line">        queryParams: &#123;</span><br><span class="line">            <span class="string">'session_id'</span>: <span class="string">'123'</span></span><br><span class="line">        &#125;,</span><br><span class="line">        fragment: <span class="string">'anchor'</span></span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">this</span>.router.navigate([<span class="string">'/news'</span>], navigationExtras);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>3. 获取 get 传值</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"> <span class="keyword">constructor</span>(private route: ActivatedRoute) &#123;</span><br><span class="line">     <span class="built_in">console</span>.log(<span class="keyword">this</span>.route.queryParams);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="10-8-父子路由"><a href="#10-8-父子路由" class="headerlink" title="10.8 父子路由"></a>10.8 父子路由</h2><p><strong>1. 创建组件引入组件</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; NewsaddComponent &#125; <span class="keyword">from</span> <span class="string">'./components/newsadd/newsadd.component'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; NewslistComponent &#125; <span class="keyword">from</span> <span class="string">'./components/newslist/newslist.component'</span>;</span><br></pre></td></tr></table></figure>
<p><strong>2. 配置路由</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    path: <span class="string">'news'</span>,</span><br><span class="line">    component: NewsComponent,</span><br><span class="line">    children: [&#123;</span><br><span class="line">        path: <span class="string">'newslist'</span>,</span><br><span class="line">        component: NewslistComponent</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">        path: <span class="string">'newsadd'</span>,</span><br><span class="line">        component: NewsaddComponent</span><br><span class="line">    &#125;]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>3. 父组件中定义 router-outlet</strong></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">router-outlet</span>&gt;</span><span class="tag">&lt;/<span class="name">router-outlet</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h1 id="十一、更多参考"><a href="#十一、更多参考" class="headerlink" title="十一、更多参考"></a>十一、更多参考</h1><ul>
<li><a href="https://www.angular.cn/guide/quickstart" target="_blank" rel="noopener">Angular中文文档</a></li>
</ul>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2019/01/06/electron-summary/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2019/01/10/ionic3-summary/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
